Destroy(gameObject) fails once in a while

Hi All!

In my game I have a mouse (the animal, not the input device :wink: ) that switches between a normal state and an insane state. So I have a normalMouse prefab and an insaneMouse prefab. These are used by an empty game object like this:

public GameObject normalMousePrefab;
public GameObject insaneMousePrefab;

public GameObject normalMouse; //empty in inspector
public GameObject insaneMouse; //empty in inspector
		
void Start () {
	ToNormalState();
}
	
public void ToNormalState(){
	normalMouse = Instantiate(normalMousePrefab) as GameObject;
	normalMouse.transform.parent = transform; //just for a well-arranged hierarchy
	if (insaneMouse != null) Destroy(insaneMouse);
}

public void ToInsaneState(){
	insaneMouse = Instantiate(insaneMousePrefab) as GameObject;
	insaneMouse.transform.parent = transform; //just for a well-arranged hierarchy 
	if (normalMouse != null) Destroy(normalMouse);		
}

This works most of the time. But sometimes the Destroy fails… so the normalMouse or the insaneMouse doesn’t disappear. Over time a lot of extra prefabs is hanging on the object.

What is wrong?
Any overall better way of doing this?

Please help! Thanx a lot in advance! :slight_smile:

The functions look good to me but then again, I do not know C#.

2 things I would do is

1: make the normal and insane mouse a private var. If it is not defined in the editor, it does not need to be public.

2: Place a Debug.Log in both functions to see when they are being called. It could be that the problem is not with your function itself but with the function that calls it. Maybe they are getting triggered multiple times or back to back. I would even make it a Debug.LogError so that it pauses the editor.

let us know if you find it.

Thanx a lot for your answer!

You’re right about the private var - I only had the normal and insane mouse public so I could see them in the inspector. And this actually got me in the right direction: After destruction the normalMouse and insaneMouse were ‘missing’ not ‘none’… I had to set them to null:

public void ToNormalState(){
	normalMouse = Instantiate(normalMousePrefab) as GameObject;
	normalMouse.transform.parent = transform; //just for a well-arranged hierarchy
	if (insaneMouse != null){
		Destroy(insaneMouse);
		insaneMouse = null;
	}
}

public void ToInsaneState(){
	insaneMouse = Instantiate(insaneMousePrefab) as GameObject;
	insaneMouse.transform.parent = transform; //just for a well-arranged hierarchy 
	if (normalMouse != null){
		Destroy(normalMouse);
		normalMouse = null;
	}
}

This works all the time! :),Thanx