- Home /
Destroy object on collision or check position
In the scenario where multiple rigidBody
s moving due to addForce
goes out of view (say, top of view) and is no longer needed then what technique should be prefered?
- Destroying the
gameObject
by detecting collisionby creating a
collider
object and destroying therigidBody
when it collides with it
Destroying the
gameObject
by first checking it'srigidBody
position inUpdate
orFixedUpdate
Premature optimization or not, I'd still like to know
Thanks,
Answer by haim96 · Sep 30, 2014 at 11:24 AM
if you looking for optimization i would use object pool and avoid instantiate\destroy. for remove unused objects of the screen i would use collider set as trigger so you don't calculate collision physics and you don't need to check things every frame (or every X frames)
learn about object pooling:
http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling
well, you technically suggested a 3rd way and... it looks like Object Pooling
is THE way to go.
Thanks, I was anyways pretty doubtful on this Instantiate-Destroy thing.
Answer by GameVortex · Sep 30, 2014 at 11:33 AM
Both are perfectly valid methods. What is preferred is subjective and depends entirely on what works best for you and your game.
The first scenario has the issue that it will be calculating collision for all objects (which have colliders) which might not be the objects you need to destroy. This can easily be solved by putting the objects in the correct layer and modifying the collision matrix so the destroyer can only detect collision from the correct rigidbodies.
The second scenario is fine, you sort of get greater control of what specific objects will be checked, but could have issues if the objects are big and then might still be in view when their root position is not. There is also some complicated calculations to do if the camera is a perspective camera (the farther away the object is the higher up can it go before it is out of view). You could also get some issues if the camera can move around. All of these issues can be easily solved. Example: Having the camera in Orthographic mode (not applicable for all games), or not moving the camera at all, or never moving the objects in depth, or if you really want a perspective camera which moves around and the object should still be destroyed when out of view you could use OnBecameInvisible callback instead of checking positions.
For a fixed orthographic camera I'd go with OnBecameInvisible
. Thanks. (Sorry, can't upvote since I don't have enough rep, for now)