Instantiated Prefab doesnt destroy

really odd issue.

Im Instantiating a dice prefab and then destroying the prefab and re instantiating to roll again with OnGUI button click.

the main issue is that after the 2nd destroy/instantiation the prefabs are no longer destroyed or registered.

code is -

void DieSpawn()
		if (GameObject.FindGameObjectWithTag("Die"))

	        //dieGameObject = null;
		// create the die prefab/gameObject
		dieGameObject = (GameObject)Instantiate(diePrefab,spawnPoint.transform.position ,Quaternion.identity)as GameObject;
		// give it a random rotation
		dieGameObject.transform.Rotate(new Vector3(Random.value * 300, Random.value * 300, Random.value * 300));
		//create reference to gameobject
		dieGameObject = GameObject.Find(dieName);
		dieValueComponent = dieGameObject.GetComponent<DieValue>();	
		//apply force
		dieGameObject.constantForce.force = new Vector3(1, 0, 1);

ideas as I just cant see whats wrong with this…

When instantiate an object, Unity adds the string “(clone)” behind his name.
If you’r property “dieName” is only the original name (without “(clone)” ), then it will not find any gameobject on the line 8 of your code.

Instead, you can rename the instantiated object so that the “(clone)” is removed → the gameobject is being found:

dieGameObject.Name.Replace("(Clone)", string.Empty);

I’m not sure why you have added the line 20, because the dieGameObject is already referencing the desired object.

If it is NOT because of the name, then there are other possibilities what could have gone wrong

  1. The prefab doesn’t have the correct tag
  2. Some other script manipulates the tag or name of the object

At least, I would reccomend you, not to use different methods to find an object (like GameObject.FindGameObjectWithTag(“Die”) and GameObject.Find(dieName))
Then you can at least be sure, that the problem is with the choosen method.

You can also debug to check if it enters the if on line 4, and if it finally finds the dieObject.

Hope I was able to help


solved the issue.

just found the solution while looking at another script for answers to another problem.

changed - Destroy(dieGameObject);

to - DestroyImmediate(dieGameObject);

and problem solved