Home > Back-end >  Unity 2D: How to add List of Collider2D inside of an if statement condition?
Unity 2D: How to add List of Collider2D inside of an if statement condition?

Time:12-15

I have a list of Collider2D filled with a bunch of Collider2D's and I want to check to see if the player collides with any of the colliders added from the Unity editor in this list. Something like this snippet here:

using UnityEngine;
public class PlayerScript : MonoBehaviour
{
    private Rigidbody PlayerRB;
    public List<Collider2D> GroundCOlliders;
    public bool IsGrounded;
    
    private void Start()
    {
        PlayerRB = GetComponent<Rigidbody2D>();
        GroundColliders = new List<Collider2D>();
    }
    private void Update()
    {
        if (PlayerRB.IsTouching(GroundColliders))
        {
            IsGrounded = true;
        }
    }
}

CodePudding user response:

The typical solution is to cast a very short ray from the player's feet downwards and seeing if it hits one of the ground colliders. Consider adding a Ground tag or even layer to check against instead of holding a list of ground colliders. Something like:

// Note the use of FixedUpdate over regular Update for physics-related calculations.
private void FixedUpdate()
{
    RaycastHit hit;
    if (Physics.Raycast(playerFeetPosition, Vector3.down, out hit, 0.25f) && hit.collider.CompareTag("Ground"))
    {
        IsGrounded = true;
    }
    else
    {
        IsGrounded = false;
    }
}

EDIT: I realize that my solution doesn't directly answer your question, but rather assumes that I know what you really want and how to do it better. For a more direct solution to your problem, look into the Physics.OverlapX family of functions.

CodePudding user response:

if you are checking ground you use checkbox, and for the colliders you can use layerMask

Vector3 playerFeetPosition;
Vector3 playerBaseSize;
layermask groundmask;

private void FixedUpdate()
{
    RaycastHit hit;
    if ( Physics.CheckBox(playerFeetPosition, playerBaseSize,Quaternion.identity, groundmask)
    {
        IsGrounded = true;
    }
    else
    {
        IsGrounded = false;
    }
}
  • Related