detect a trigger one time per collision
In my game there are 2 players, Player1-a and Player2, when the players collide, the text on each one of them is changing (Player1-a is Player1 and Player2 is Player2-a). The problem is that it keeps changing texts while the players are colliding (it can switch the texts 2 times for one collision) and i want it to change the texts only one time per collision. And I also need that after a collision it wont be able change texts for 5 seconds because if they will collide again after 1 second it will change the texts again). This is the player1 collision action:
  void OnTriggerEnter2D(Collider2D other)
      {
          if (other.CompareTag("TriggerOn"))
          {
              if (firstPlayerText.text == "Player1-a")
              {
                  firstPlayerText.text = "Player1";
                  secondsPlayerText.text = "Player2-a";
              }
          }
      }
and this is the collision action of the other player:
  void OnTriggerEnter2D(Collider2D other)
      {
          if (other.CompareTag("TriggerOn2"))
          {
              if (secondsPlayerText.text == "Player2-a")
              {
                  firstPlayerText.text = "Player1-a";
                  secondsPlayerText.text = "Player2";
              }
          }
      }
By the way I also want that after the collision, the player2 with the new text (player2-a) wont be able to move for 5 seconds.
Answer by UnityCoach · Apr 14, 2017 at 10:03 AM
When two objects collide with each other, both receive the collision information.
So, the best practice is to have only one of those patterns :
- object minds its own business, does things to itself but leaves the other one alone 
- object does things to the other object, but does nothing to itself 
Or you can also use if (gameObject.GetInstanceID() < other.gameObject.GetInstanceID()) to do things only on one of the two by comparing their InstanceID which will always be unique. As GetInstanceID() has a cost, you can also do it only when (gameObject.tag == other.gameObject.tag). Like : 
 if (gameObject.tag != other.gameObject.tag || gameObject.GetInstanceID() < other.gameObject.GetInstanceID())
 {
     // we're different or I was first, I handle collision
 }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                