0
\$\begingroup\$

I was attempting to create a simple button prompt where when you are inside a 2d box colider it will give you the option to press the button within that range, below is the short code used to test this.

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

public class ButtonScript : MonoBehaviour
{

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("ENTER");
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        Debug.Log("Stay");
        if (collision.gameObject.tag == "Player")
        {
            Debug.Log("PLayer Detected");
            if (Input.GetKeyDown(KeyCode.E)) {
                Debug.Log("E pressed");
            }
        }
    }
}

However this does not output any Debug Messages at all. Maybe i have a misundestanding of the Is Trigger function and colliders in general but when i have it turned off it does nothing, when i have it on it acts as a box (which i dont want) but when i push againsts the box it will send out the debug messages.

enter image description here

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

A Trigger collider does not generate collision response (which is what the OnCollisionEnter/Stay/Exit messages and their 2D versions handle).

It only participates in overlap checks, which are handled by the OnTriggerEnter/Stay/Exit messages and their 2D versions.

So replace your code with:

private void OnTriggerEnter2D(Collider2D other)
{
    Debug.Log("ENTER");
}

private void OnTriggerStay2D(Collider2D other)
{
    Debug.Log("Stay");
    if (other.CompareTag("Player"))
    {
        Debug.Log("PLayer Detected");
        if (Input.GetKeyDown(KeyCode.E)) {
            Debug.Log("E pressed");
        }
    }
}

Just watch out that in the physics step (when these collision/trigger callback messages are fired), the key press events you're receiving are those from the previous frame. In recent Unity versions, the freshest input isn't available until Update.

Also note that these messages are sent only if one of the participating colliders is attached to a Rigidbody / Rigidbody2D - check the collision action matrix for the full details.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks so much for the quick response! That works! \$\endgroup\$
    – ConnnK
    Commented May 25, 2020 at 15:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .