Simple script to check “Does this object collide nothing” in Unity

In Unity it is very easy to check object collision but If you want to check that Object didn’t collide anything, You need to do some trick.

Here is my solution:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColliderCheckHit : MonoBehaviour {

public List<Collider> listStayTriggerCollider = new List<Collider>();
public Collider selfCollider;
void Start()
{
selfCollider = this.GetComponent<Collider>();
}

void OnTriggerStay(Collider other)
{
if(!listStayTriggerCollider.Contains(other))
{
listStayTriggerCollider.Add(other);
}

}

void LateUpdate()
{
listStayTriggerCollider.Clear();
}

}

Usage

Other script can access listStayTriggerCollider to check how many object collide to this object, If size of a list is zero, It collide nothing.

Code Explain

In OnTriggerStay() we add the collider that stay in this trigger to listStayTriggerCollider and we clear the list in LateUpdate() to let other script access the listStayTriggerCollider in Update() before the list is empty.

Q: Why don’t you just use build in Physics function(OverlapSphere/BoxOverlap)?

A: I think it easier to adjust the size of the collider in editor than adjust the parameter in code.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade