- Home /
Cannot destroy Component while GameObject is being activated or deactivated
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 :
// OnDisable
if (_meshRenderer != null)
{
DestroyImmediate(_meshRenderer);
_meshRenderer = null;
}
// OnWillRenderObject()
// 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 !
Answer by adarshnambiar · Mar 22, 2017 at 09:38 PM
In that case instead of destroying the MeshRenderer component.Maybe you can just disable it ?
Answer by PPenar · Mar 22, 2017 at 09:25 PM
Don't use DestroyImmediate as it is an unsafe function and may cause unpredictable behaviour. Use
Destroy(_meshRenderer);
instead.
this doesn't work because then it says Destroy may not be called from edit mode! Use DestroyImmediate ins$$anonymous$$d.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Access water4 scripts via my script? 1 Answer
The name "Destory" Does not exist in the current context 2 Answers
2D C# destroy a GameObject on collision 2 Answers
How can I add the OnTriggerEnter function to all game objects that I instantiate? 1 Answer