Compare Tag on Collision (Collider.CompareTag)
Hi all,
First time poster, forums have been a great help to me.
I have encountered this issue, and after trying a few combinations I need to ask for help!
I want to compare tag with the object I'm colliding with, I have the below code, but it seems to just ignore all collisions, let alone whatever I want it to collide with, my debug log also does not come up in console.
If you're wondering why I play with gravity, i have a floating companion that I use as a grenade.
If i remove the If statement everything works as intended, but it will obviously instantiate my explosion on every contact.
TLDR: want instantiation to happen only with collision with Enemy tags.
void OnCollisionEnter(Collider col) {
if (col.CompareTag("Enemy"))
{
Instantiate (explode, location.position, transform.rotation);
Debug.Log ("awake");
}
rbody.useGravity = false;
}
Answer by Cepheid · Nov 17, 2016 at 09:55 PM
The argument type you've passed into the OnCollisionEnter () callback is wrong.
The OnCollisionEnter () method requires a datatype of Collision not Collider.
The Collider datatype is only used for OnTriggerEnter/Exit/Stay () callbacks.
Also, when you use the Collision class you must access the CompareTag () method from the gameObject that the Collision belongs to. For example, your code would now look like the following:
void OnCollisionEnter (Collision col)
{
if (col.gameObject.CompareTag("Enemy"))
{
Instantiate (explode, location.position, transform.rotation);
Debug.Log ("awake");
}
rbody.useGravity = false;
}
Answer by Wolverine-X-man · Oct 20, 2020 at 07:02 AM
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Enemy"))
{
print("Enemy Detected");
_gameOver = true;
}
}