In any given game, you are probably going to find dozens, if not hundreds of different objects colliding or intersecting with one another. Hence, one of the first things you learn in Unity is how to identify the type of object you have touched. These are the most common ways to do so among beginners:
void OnTriggerEnter(Collider other) {
// If a GameObject has an "Enemy" tag, remove him.
if(other.tag == "Enemy") {
Destroy(other.gameObject);
}
}
void OnCollisionEnter(Collision collisionData) {
// If a GameObject has an "Enemy" tag, remove him.
if(collisionData.collider.tag == "Enemy") {
Destroy(other.gameObject);
}
}
Essentially, the idea is checking whether the object we are colliding with or touching has been labelled with an Enemy tag, before we perform any action on the object.
While it is simple and easy-to-understand, there are better ways of identifying objects we are colliding with.
Continue reading