Problem with destroying instanced objects (23353)

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?

Ok Ill be here if you need more help

1 Answer

1

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.

Yeah I don't understand.... Everything works perfectly fine in the Test scene, I've even made my player in my Main Scene the same as in the Test scene and nothing. This seriously makes no sense.