Search Unity

How to check for a collision with any object in array?

Discussion in 'Scripting' started by thelonelypanda, Jan 12, 2019.

  1. thelonelypanda

    thelonelypanda

    Joined:
    Aug 11, 2016
    Posts:
    4
    I've been trying to figure out how to check if a specific GameObject's BoxCollider2D is touching any GameObject's BoxCollider2D that has a specific tag.

    example:
    How to check if my player's feet BoxCollider2D is touching any GameObject's(with tag "Ground") BoxCollider2D
     
  2. thelonelypanda

    thelonelypanda

    Joined:
    Aug 11, 2016
    Posts:
    4
    Well, I found the answer to my own problem. So for anyone who ever has the same problem as me here you go! :)

    To follow my example:
    Code (CSharp):
    1. public class PlayerController : MonoBehaviour {
    2.  
    3.     private Rigidbody2D playerRB;
    4.     private BoxCollider2D playerFeetBC;
    5.     private GameObject[] groundBCs;
    6.     private BoxCollider2D groundBC;
    7.  
    8.     private bool canJump = false;
    9.  
    10.     void Start () {
    11.         playerRB = GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>();
    12.         playerFeetBC = GameObject.Find("PlayerFeet").GetComponent<BoxCollider2D>();
    13.         groundBCs = GameObject.FindGameObjectsWithTag("Ground");
    14.  
    15.     }
    16.  
    17.     void FixedUpdate () {
    18.         if (Input.GetKeyDown(KeyCode.W))
    19.         {
    20.             JumpCheck();
    21.             if (canJump == true)
    22.                 playerRB.velocity = new Vector2(playerRB.velocity.x, 5 * playerSpeed);
    23.         }
    24.     }
    25.  
    26.     private void JumpCheck()
    27.     {
    28.         for (int i = 0; i < groundBCs.Length; i++)
    29.         {
    30.             groundBC = groundBCs[i].GetComponent<BoxCollider2D>();
    31.             if (playerFeetBC.IsTouching(groundBC))
    32.             {
    33.                 canJump = true;
    34.                 break;
    35.             }
    36.             else
    37.                 canJump = false;
    38.         }
    39.     }
    40. }
     
  3. swordiguy

    swordiguy

    Joined:
    Dec 7, 2020
    Posts:
    2
    You can also do this way shorter

    int i = 0; //this is our index;
    public GameObject[] desiredGameObject;

    private void OnTriggerEnter(Collider other)
    {
    if(other.transform == desiredGameobject.transform)
    {
    //Execute code here
    }
    }
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    Please don't necropost. This thread was resolved and is over 4 years old now.

    Thanks.