- Home /
Problem with destroying instanced objects
I want to instantiate an object and whenever I instantiates a new object I want objects who share the same tag with the new object to be destroyed. I got the following lines of code
instance = Instantiate(Resources.Load(targetModel)) as GameObject;
Destroy(gameObject.FindWithTag(instance.tag));
The problem as you might see by looking at the code is that the instance is destroyed right after its been made. I always want the latest instance to remain.
I tried to switch places like below, but then I get this error: "UnassignedReferenceException: The variable instance of 'mousePosition' has not been assigned."
Destroy(gameObject.FindWithTag(instance.tag));
instance = Instantiate(Resources.Load(targetModel)) as GameObject;
So how do I solve this problem?
Answer by aldonaletto · Jun 19, 2011 at 11:07 PM
You can't use instance.tag because it was not assigned yet. Replace it with another variable containing the tag:
Destroy(gameObject.FindWithTag(targetTag));
instance = Instantiate(....
You must define previously the tag you want to kill in the targetTag variable.