Remove MeshFilter raises MissingReferenceException

Hi,

I’ve tried to find my answer, but I can’t find anything.

So I’m working on an edit-time grid generator and I have two buttons: Generate and Destroy.
When I click on Destroy, I call the clean() function which removes the MeshFilter and MeshRenderer components. However, when I try to do that (with DestroyImmediate since I’m in editor mode) the following error message is printed on the console:

MissingReferenceException: The object of type ‘MeshFilter’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEditor.Editor.IsEnabled () (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:530)

The code is pretty simple, here it is:

public void clean()
{
    MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
    if (meshRenderer != null)
    {
#if UNITY_EDITOR
        DestroyImmediate(meshRenderer);
#else
        Destroy(meshRenderer);
#endif
    }

    MeshFilter meshFilter = GetComponent<MeshFilter>();
    if (meshFilter != null)
    {
#if UNITY_EDITOR
        DestroyImmediate(meshFilter);
#else
        Destroy(meshFilter);
#endif
    }
}

Where am I wrong?

Community op.

I’ve resolved this problem by avoiding the destroying. I just remove the elements by assigning new values.

public void cleanMesh()
{
    MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
    meshRenderer.sharedMaterials = new Material[0];
   
    MeshFilter meshFilter = GetComponent<MeshFilter>();
    if (meshFilter.sharedMesh != null)
    {
        DestroyImmediate(meshFilter.sharedMesh);
        meshFilter.sharedMesh = null;
    }
}
1 Like

I think you should ignore this Exception.
It’s just editor inspector drawing bug.
You have in inspector components: your object, mesh filter.
After your object destroy mesh filter (with button in inspector gui), inspector is trying to draw inspector gui for mesh filter which is deleted.
If in inspector components will be in order: mesh filter, your object, there won’t be Exception.

1 Like