r/unity • u/MalgorgioArhhnne • 14d ago
Coding Help GameObject.FindGameObjectsWithTag gets an array with the same length after one of the objects has been destroyed.
I would have thought that after destroying one of the objects with the relevant tag, the array would become shorter. The array remained the same length after the object was destroyed, so I thought I would paste the same statement at the point in the code after the object has been destroyed. However, it's still the same length, and the entry with that index is now a stale object. Other indexes still refer to the same objects, which I also don't understand. I even tried setting the array size to zero before the GameObject.FindGameObjectsWithTag statement. I want to reset the array to only include objects that still exist. Any help?
5
u/Competitive-Elk763 14d ago edited 14d ago
It does only give objects that exist. Your code is incorrect or there are other objects with that tag in the scene.
Note that destroy waits until the end of the frame to trigger, it is actually marking the object for removal in the current frame. So you can't do both on the same frame.
There is DestroyImmediate to immediately destroy but you shouldn't use that.
11
u/vanit 14d ago
Are you using DestroyImmediate? Otherwise references will persist for the rest of that frame. It's probably better that your code just doesn't depend on that functionality.
1
u/eminsefa 13d ago
Don’t use it anyway. Use a list (and a helper manager script if needed), add and remove objects to that list when they are enabled-disabled/created-destroyed. Hashlist is better regarding of your need. You never need find methods, don’t use them
Edit: If it’s editor script, it’s fine to use it. Then DestroyImmediate is the answer
2
u/johnv_dev 14d ago
destroy doesn't actually remove the object until the end of the frame, so if you call FindGameObjectsWithTag right after it, the dead one is still in there. easiest fix is to call SetActive(false) on it right before Destroy, since FindGameObjectsWithTag skips inactive objects. then the new array will only have the live ones.
1
u/snipercar123 14d ago
It takes one frame to fully destroy a gameObject, could this be something you missed?