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)
	_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 !

In that case instead of destroying the MeshRenderer component.Maybe you can just disable it ?

Don’t use DestroyImmediate as it is an unsafe function and may cause unpredictable behaviour.