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:
    3
    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:
    3
    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. }