In any collision, there are two GameObjects involved right? What I want to know is, How do I decide which object should contain my OnCollision*
?
As an example, let's suppose I have a Player object and a Spike object. My first thought is to put a script on the player that contains some code like this:
OnCollisionEnter(Collision coll) {
if (coll.gameObject.compareTag("Spike")) {
Destroy(gameObject);
}
}
Of course, the exact same functionality can be achieved by instead having a script on the Spike object that contains code like this:
OnCollisionEnter(Collision coll) {
if (coll.gameObject.compareTag("Player")) {
Destroy(coll.gameObject);
}
}
Whilst both are valid, it made more sense to me to have the script on the Player because, in this case, when the collision happens, an action is being performed on the Player.
However, what's making me doubt this is that in future you may want to add more objects that will kill the Player on collision, such as an Enemy, Lava, Laser Beam, etc. These objects will likely have different tags. So then the script on the Player would become:
OnCollisionEnter(Collision coll) {
GameObject other = coll.gameObject;
if (other.compareTag("Spike") || other.compareTag("Lava") || other.compareTag("Enemy")) {
Destroy(gameObject);
}
}
Whereas, in the case where the script was on the Spike, all you would have to do is add that same script to all the other objects that can kill the Player and name the script something like KillPlayerOnContact
.
Also, if you have a a collision between the Player and an Enemy, then you likely want to perform an action on both. So in that case, which object should handle the collision? Or should both handle the collision and perform different actions?
I have never built a game of any reasonable size before and I'm wondering if the code can become messy and difficult to maintain as it grows if you get this sort of thing wrong in the beginning. Or maybe all ways are valid and it doesn't really matter?
Any insight is much appreciated! Thank you for your time :)
Tag.SPIKE
instead? \$\endgroup\$