- Home /
Looking for gameObjects in the update function
Some Items are destroyable in my game. When they are destroyed, I want them to respawn, forcing there to always be at least one of those objects in the scene.
I want to do this by calling FindGameObjectWithTag in the update function and instantiating the object if it returns null.
However, something tells me that calling FindGameObjectWithTag on every frame might not be wise. Is there another function I should do this in? Or perhaps an entirely different, more optimized method to respawn objects?
Thanks in advance!
Answer by ShadyProductions · May 23, 2020 at 09:59 PM
Why don't you just re instantiate another of the item, after you call destroy on the item? That way you don't need to do anything in update.
I can't say I'm entirely sure what you mean. How can I call Instantiate on an object that has been destroyed? Does the script finish running before the object destroys or will all lines after the destroy function be ignored?
Also, my objects are being dropped off an edge of sorts and being destroyed by a "death Barrier" trigger collider. In other words, the dropped object is being destroyed by another object. Will this get in the way of re instantiation? Perhaps I should have the object check its position and destroy itself when it drops below a certain y value. Would this be a better approach?
Why think so hard about this, you have a script that does something like this right?:
public void OnCollisionEnter(Collision collision)
{ // deathbarrier
Destroy(collision.gameObject);
}
all u have to do is instantiate a copy of the gameobject, or even beter, just reset the object ins$$anonymous$$d of destroy it, but that's up to you.
public void OnCollisionEnter(Collision collision)
{
var copy = Instantiate(collision.gameObject, new Vector3(0,0,0), Quaternion.identity);
Destroy(collision.gameObject);
}
Or KoenigX3 answer is also viable, if you only want to instantiate new objects if they fall below a certain threshold of active objects in scene.
Answer by KoenigX3 · May 24, 2020 at 09:58 AM
You could create a DestroyableObjectManager class, which has the references to all the destroyable objects in your screen. This could be done by using a Dictionary with GameObject key and bool value. Also, it could be a good idea to create an integer variable in this class, which will store the number of currently active destroyable GameObjects.
Whenever you destroy an object, call a function of this class, in which you can set the reference of the GameObject to null and decrease the counter.
That way you can use the counter to check how many objects are currently active in the scene. If there isn't enough objects, you can check your dictionary, and re-instantiate some of the objects which are null (destroyed). The reason why we are using Dictionary here is that you can look for the GameObject using a reference, and you don't have to iterate through a List to find it.