3
\$\begingroup\$

To destroy GameObjects I'm using this code :

try
        {
            DestroyImmediate(g);
        }
        catch (Exception e)
        {
            Destroy(g);
        }

It is giving me error, something like this :

enter image description here

Full code :

using System;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class Road : MonoBehaviour
{
    public List<Vector3> points = new List<Vector3>();
    public List<GameObject> gameObjects = new List<GameObject>();
    void Start()
    {

    }
    void OnValidate()
    {
        foreach(GameObject g in gameObjects)
        {
            try
            {
                DestroyImmediate(g);
            }
            catch (Exception e)
            {
                Destroy(g);
            }
        }
        gameObjects.Clear();
        foreach (Vector3 point in points)
        {
            GameObject tem = GameObject.CreatePrimitive(PrimitiveType.Cube);
            tem.transform.position = point;
            tem.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
            tem.transform.parent = gameObject.transform;
            gameObjects.Add(tem);
        }
    }
}
\$\endgroup\$
4
\$\begingroup\$

The red you see in your console is not an exception, it's an internal unity error. so that try catch doesn't help. You can't destroy gameObjects in that frame. You have to delay your call until the next frame. you can achieve this with coroutines.

using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

[ExecuteInEditMode]
public class Road : MonoBehaviour
{
    public List<Vector3> points = new List<Vector3>();
    public List<GameObject> gameObjects = new List<GameObject>();
    void Start()
    {

    }
    void OnValidate()
    {
        foreach(GameObject g in gameObjects)
        {
            StartCoroutine(DestroyGameObject(g));
        }
        gameObjects.Clear();
        foreach (Vector3 point in points)
        {
            GameObject tem = GameObject.CreatePrimitive(PrimitiveType.Cube);
            tem.transform.position = point;
            tem.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
            tem.transform.parent = gameObject.transform;
            gameObjects.Add(tem);
        }
    }

    IEnumerator DestroyGameObject(GameObject g) 
    {   
        yield return null;
        DestroyImmediate(g,true);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.