Home > Net >  Unity collision of one object with another
Unity collision of one object with another

Time:05-10

I have a code, I need that when the player_ object touches the object with the bomb tag, the following actions occur, but when the bg_ object touches the object with the bomb tag, nothing should happen, how to write it?

public class Player_ : MonoBehaviour{

public GameObject player_;
public GameObject bg_;

public static bool lose = false;

void Awake(){
    lose = false;
}

void OnTriggerEnter2D (Collider2D other){
    if (other.gameObject.tag == "bomb")
        lose = true;
        player_.gameObject.SetActive (false);
        bg_.gameObject.SetActive (false);

}

}

CodePudding user response:

While tags will work for your need, I'd like to caution against using them.

Instead, utilize Layer Based Collision, and use layers instead of tags. This effectively does the same thing, but it actually prevents physics interactions entirely, preventing wasted computing power.

Rather than adding a tag to the player, instead create a layer for "Player" and a layer for "Interactables" (or "Bombs" if you only have the player interacting with bombs). Set the layers respectively, and modify the collision matrix so that only things on the Player can collide with Interactables. This way, other objects won't even trigger a collision and you don't need to build logic to ignore it.

CodePudding user response:

On your bomb, you could have a OnTriggerEnter2D and when something triggers it, you simply look the tag and do the proper reaction.

void OnTriggerEnter2D (Collider2D other){
    if (other.gameObject.tag == "Player")
    {
        Do Something();
    }
}

This way, when something else triggers it, nothing happen

  • Related