- Home /
Trigger won't detect when I press a button
I have two gameobjects.
One is a Player tagged "Player". With a rigidbody, a capsule collider 2D and everything.
The other one is a button with a capsule collider 2D and a box collider 2D labeled "Is Trigger".
When I'm inside the trigger and press "E", it sometimes works and sometimes doesn't. It detects the trigger, because I have set a bool to know it.
What am I missing?
public class HubButtonScript : MonoBehaviour
{
public SpriteRenderer SpriteRen;
public Sprite Button2;
public bool isInside = false;
// Start is called before the first frame update
void Start()
{
SpriteRen = GetComponent<SpriteRenderer>();
}
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
isInside = true;
if (Input.GetKey(KeyCode.E))
{
PressButton();
Debug.Log("Button Pressed");
}
}
}
private void PressButton ()
{
SpriteRen.sprite = Button2;
}
}
It was the first thing I tried, but it still doesn't work.
Answer by Marhola · Aug 05, 2020 at 12:27 PM
I got it solved.
There were two errors.
First, I had two colliders with diferent purposes. I had to create a child and add the capsule collider to it, deleting the parent's one.
Second, I wasn't calling Input.GetKey in the Update method. I called it there using isInside and now it works fine every time.
Your answer
Follow this Question
Related Questions
OnTriggerEnter not trigger after ios build 0 Answers
Box Collider 2D "Is Trigger" Help! 1 Answer
BoxCollider2D, Trigger not working 1 Answer
Weird 2d collision behaviour 1 Answer