Matt O'Connell Matt O'Connell - 3 months ago 15
C# Question

Unity3D C#: OnTriggerEnter setting to only one tag?

I was creating a simple scene in Unity3D today where a player would choose their colour by colliding into a wall, which would change the tag of the player to 'RedPlayer', 'BluePlayer', etc; And print on the Debug Log saying 'He's a red boy!', or whatever the player chose. However, everything thing was working fine until I added the last wall in (WhitePlayer), and every wall changed the Player's tag to WhitePlayer, however it still prints the colour of the wall they collide with.

using UnityEngine;
using System.Collections;


public class ColourChoice : MonoBehaviour
{

void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "RedCollision")
Debug.Log("He's a Red Boy!");
gameObject.tag = "RedPlayer";

if (other.gameObject.tag == "YellowCollision")
Debug.Log("He's a Yellow Boy!");
gameObject.tag = "YellowPlayer";

if (other.gameObject.tag == "BlueCollision")
Debug.Log("He's a Blue Boy!");
gameObject.tag = "BluePlayer";

if (other.gameObject.tag == "GreyCollision")
Debug.Log("He's a Grey Boy!");
gameObject.tag = "GreyPlayer";

if (other.gameObject.tag == "GreenCollision")
Debug.Log("He's a Green Boy!");
gameObject.tag = "GreenPlayer";

if (other.gameObject.tag == "MaroneCollision")
Debug.Log("He's a Marone Boy!");
gameObject.tag = "MaronePlayer";

if (other.gameObject.tag == "PurpleCollision")
Debug.Log("He's a Purple Boy!");
gameObject.tag = "PurplePlayer";

if (other.gameObject.tag == "OrangeCollision")
Debug.Log("He's a Orange Boy!");
gameObject.tag = "OrangePlayer";

if (other.gameObject.tag == "WhiteCollision")
Debug.Log("He's a White Boy!");
gameObject.tag = "WhitePlayer";
}
}


I've included the code here, hoping someone can figure it out. If I could get an explanation on how to fix this, that would be great.

Thanks,
Matt

Answer

Your code was already bad before you added the WhiteCollision tag check. This is a typical mistake by new programmers.

Without the open and closing braces after each if statement, the Debug.Log will only run if the if statement is true. Other code under the Debug.Log will execute regardless of if the if statement on top of it is true or not.

You must put the if statement code that will execute if something is true in a curly braces {} if you want multiple lines of code to execute.

So

   if (other.gameObject.tag == "RedCollision")
   Debug.Log("He's a Red Boy!");
   gameObject.tag = "RedPlayer";

should be

if (other.gameObject.tag == "RedCollision"){
    Debug.Log("He's a Red Boy!");
    gameObject.tag = "RedPlayer";
}

Do this for each of the if statements in your code.

Tom improve your code, use if (other.gameObject.CompareTag("RedCollision")) to compare tags.