Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

OnCollisionEnter Problems

Discussion in 'Scripting' started by murgntheurgn, Apr 30, 2020.

  1. murgntheurgn

    murgntheurgn

    Joined:
    Oct 12, 2019
    Posts:
    8
    I'm trying to make an object change a bool to true when a game object touches it with a specific tag i give it but its changing the bools to true when anything touches it. If i could have some help that would be great, thank you. Here's my code for anyone reading this :) :

    Code (CSharp):
    1. {
    2.     public string strTag;
    3.     public string strTag2;
    4.     public bool player1Dead;
    5.     public bool player2Dead;
    6.  
    7.     private void Start()
    8.     {
    9.         player1Dead = false;
    10.         player2Dead = false;
    11.     }
    12.     private void OnCollisionEnter(Collision collision)
    13.     {
    14.         if (collision.collider.tag == strTag)
    15.             Debug.Log("Player 2 Wins!");
    16.             player1Dead = true;
    17.  
    18.         if (collision.collider.tag == strTag2)
    19.             Debug.Log("Player 1 Wins!");
    20.             player2Dead = true;
    21.     }
    22. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    If you don't use curly braces to encapsulate the code after your if statement into a block, then only the first statement after the if clause will be conditional. Try this:
    Code (CSharp):
    1.         if (collision.collider.tag == strTag) {
    2.             Debug.Log("Player 2 Wins!");
    3.             player1Dead = true;
    4.         }
    5.         // May as well make this "else if" since the tag can't be two things at once
    6.         else if (collision.collider.tag == strTag2) {
    7.             Debug.Log("Player 1 Wins!");
    8.             player2Dead = true;
    9.         }
    Also, using CompareTag is a little more efficient than getting the tag and doing your own comparison, so I would suggest this:
    Code (CSharp):
    1.         if (collision.collider.CompareTag(strTag)) {
    2.             Debug.Log("Player 2 Wins!");
    3.             player1Dead = true;
    4.         }
    5.         // May as well make this "else if" since the tag can't be two things at once
    6.         else if (collision.collider.CompareTag(strTag2)) {
    7.             Debug.Log("Player 1 Wins!");
    8.             player2Dead = true;
    9.         }
     
    murgntheurgn likes this.
  3. murgntheurgn

    murgntheurgn

    Joined:
    Oct 12, 2019
    Posts:
    8
    Thank you for this! It works perfectly fine now! :)