Klink45 Klink45 - 3 months ago 9
C# Question

Why are my tags not working?

I have been tearing my hair out over this! Inside of Unity, I am trying to make it so if the object the player collides with has a "Kill" tag, the player respawns. This is turning into a very hard task, because for no apparent reason this does not work:

void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
count = count + 1;
SetCountText();
audio.Play();
}
else if (other.gameObject.CompareTag("Kill"))
{
Respawn();
}
}


It seems that if I use any other tag besides
"Pick Up"
, it will simply not detect it at all. I have even tried reversing the tags and adding them to different objects to no avail!

My
Respawn()
function is also working correctly. Adding this above the line doesn't send anything to the console:

Debug.Log("Respawn");
Respawn();


I am also certain I am checking for the right tag in the script, as I have copied and pasted it from the Unity Inspector window. Do you see anything wrong here?

Inspector Window

Also, here are the settings for the
RigidBody
inside of my obbject:
RigidBody

Everything looks like it should be working fine, but it doesn't. Why is this and how can I fix it?

Answer

This is a logical error. Remove the else statement. With the else statement, if the first if statement is true, it won't check the next if statement.

if (other.gameObject.CompareTag("Pick Up"))
{
    other.gameObject.SetActive(false);
    count = count + 1;
    SetCountText();
    audio.Play();
}

if (other.gameObject.CompareTag("Kill"))
{
    Respawn();
}

EDIT:

Make sure that your GameObject with the Kill tag has its Is Trigger property checked. Also make sure there is a Rigidbody attached to that GameObject.

Comments