Check if Game Object is on a specific Collider [SOLVED]

Hey guys, I’m a big newbie with C# and I’m currently struggling with a big problem. I have a Game Object which is moving over named colliders without mesh renderers (invisible). Now basically want to check on which collider the object is currently on. Is there any possibility to do that with an if statement?
I appreciate any help.

An example code would be very nice though.

Try tagging the collider with a specific tag in Unity and checking for that tag in your player script maybe? I am a newb too, so maybe we can figure this out together. lol

When you define a collision callback on the object, you get a reference to the other collider involved in the collision. You can save a reference to that collider OnEnter and remove the reference OnExit.

private Collider2D currentCollider;

private void OnTriggerEnter2D(Collider2D other)
{
    this.currentCollider = other;
}

private void OnTriggerExit2D(Collider2D other)
{
    if(this.currentCollider == other)
    {
        this.currentCollider = null;
    }
}

To identify a collider, for instance, if one collider is a “FinishLine” or something, then you should give that collider object a new component called “FinishLine”. Then you can run code that looks something like this:

// check if the current collider has the FinishLine component
public bool AtFinishLine()
{
    return this.currentCollider != null && this.currentCollider.GetComponent<FinishLine>() != null;
}

It’s much easier and more robust to identify an object by what components it has, rather than it’s name or tag. Objects can have multiple components, but only one name or tag, which are also subject to typos and changes.

Yea that was also my thought. I found a solution now, but thank you for answering :slight_smile:

Thank you for your reply! I solved the problem with ray casting now.

1 Like