Search Unity

Cannot destroy Component while GameObject is being activated or deactivated

Discussion in 'Scripting' started by Blackfire-Studio, Mar 22, 2017.

  1. Blackfire-Studio

    Blackfire-Studio

    Joined:
    Dec 17, 2013
    Posts:
    185
    Hi there,

    I am trying to destroy a MeshRenderer component of its GameObject when the OnDisable function is raised.

    It works well when I deactivate the concerned component with the inspector, the MeshRenderer is destroyed. But when I try to deactivate the GameObject itself, OnDisable is called but I am getting this error : "Cannot destroy Component while GameObject is being activated or deactivated." and the MeshRenderer component is not destroyed.

    Here are some code snippet :

    Code (CSharp):
    1.  // OnDisable
    2. if (_meshRenderer != null)
    3. {
    4.     DestroyImmediate(_meshRenderer);
    5.     _meshRenderer = null;
    6. }
    7.  
    8. // OnWillRenderObject()
    9. // Do some rendering stuff such as DrawMesh
    Is there a workaround to destroy the MeshRenderer component when the GameObject is deactivated ? Why am I getting this error ?

    Thanks !
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Is there a reason you want to do this? A MeshRenderer on a deactivated GameObject might as well be destroyed.

    I can see some weird possibilities with using a coroutine to destroy the Renderer next frame. But I really don't see the point.
     
  3. Blackfire-Studio

    Blackfire-Studio

    Joined:
    Dec 17, 2013
    Posts:
    185
    Thanks for the answer @BoredMormon. I am using a mesh renderer to have access to OnWillRenderObject.
     
    Last edited: Mar 22, 2017