D.Super Fireball
D.Super Fireball

Reputation: 45

Unity 5.6 2D- How can I check if 2 colliders isn't touching any other collider?

In Unity 5.6 C#, I know there is a way to check for if a collider is being touched by any other collider by using IsTouching.

However, I would like to know how to group two colliders together(that are touching each other), and how to check if they both are touching any collider besides each other.

Upvotes: 0

Views: 1440

Answers (1)

derHugo
derHugo

Reputation: 90852

I will give it a shot with the idea I mentioned in the comments (I see it is hard to understand with only the comments section).

I would use a list of collisions and store any touches here, filtering out the "partner" collider using OnCollisionEnter and OnCollisionExit.

Since both are attached to the same GameObject it is easy to filter them:

public class Collisions : MonoBehaviour
{
    // Show in the Inspector for debug
    [SerializeField] private List<Collider> colliderList = new List<Collider>();

    public bool IsTouching => colliderList.Count != 0;

    private void Awake ()
    {
        // Make sure list is empty at start
        colliderList.Clear();
    }

    private void OnCollisionEnter(Collision collision)
    {
        // Filter out own collider
        if(collision.gameObject == gameObject) return;

        if(!colliderList.Contains(collision.collider) colliderList.Add(collision.collider);
    }

    private void OnCollisionExit(Collision collision)
    {
        // Filter out own collider
        if(collision.gameObject == gameObject) return;

        if(colliderList.Contains(collision.collider) colliderList.Remove(collision.collider);
    }
}

Typed on smartphone but I hope the idea gets clear

Upvotes: 1

Related Questions