Search Unity

ignore ALL collision except "Player" Tag?

Discussion in '2D' started by RuneShiStorm, Mar 18, 2018.

  1. RuneShiStorm

    RuneShiStorm

    Joined:
    Apr 28, 2017
    Posts:
    264
    Yo!
    I've got this door that close when the Player collide with a boxCollider.
    But that door also react on ALL other object that touches is :S (bullet prefabs, enemies, etc)
    How do I tell the Script to ONLY react on Tag = "Player"?
    I thought this would work but no :(

    Code (csharp):
    1.  
    2.   void OnTriggerEnter2D(Collider2D Player)
    3.     {
    4.         if (tag == "Player" && !dangerMode) //when player walk into this boxxollider it will trigger it set to start.
    5.             dangerMode = true;
    6.  
    Any idea?

    At this point I've put an "Ignore Script" on the boxcollider but its such a pain to fill out a list of things that could hit it... Looks like this.. I know it looks Noobish but Maybe I can turn it into a "list"? if so, any idea how to make a list?

    Code (csharp):
    1.  
    2.     [SerializeField]
    3.     public Collider2D other;
    4.     [SerializeField]
    5.     public Collider2D other1;
    6.     [SerializeField]
    7.     public Collider2D other2;
    8.  
    9.     private void Awake ()
    10.     {
    11.         //Physics2D.IgnoreCollision(GetComponent<CapsuleCollider2D>(), other, true);
    12.         Physics2D.IgnoreCollision(GetComponent<Collider2D>(), other, true);
    13.         Physics2D.IgnoreCollision(GetComponent<Collider2D>(), other1, true);
    14.         Physics2D.IgnoreCollision(GetComponent<Collider2D>(), other2, true);
    15.     }
    16.  

    Thanks in advance!
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    if (Player.gameObject.tag == "Player" &&
     
    RuneShiStorm likes this.
  3. furroy

    furroy

    Joined:
    Feb 24, 2017
    Posts:
    93
    You had the right idea, but you need to check the tag on what the box collided with, not the tag of the box itself.


    // this goes in a script on the box
    public void OnCollisionEnter2D(Collision2D collision)
    {
    if (collision.gameObject.tag == "Player")
    {
    // the player hit me
    }
    }
     
    RuneShiStorm likes this.
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Just adding this: using 'CompareTag' is a bit better than comparing by '==' (no allocation is made).
     
    RuneShiStorm likes this.
  5. RuneShiStorm

    RuneShiStorm

    Joined:
    Apr 28, 2017
    Posts:
    264
    Thanks guys!
    Bedtime here in tokyo but will look into it tomorrow!