- Home /
Detecting a Button Press While in a Trigger
For practice, I'm trying to detect a button press when within a trigger (like if you were to speak to an NPC in a game), but, for some reason, it isn't working. I can get an event to happen when I enter the trigger and I can get an event to happen when I press the button, but I can't get an event to happen when I am within a trigger AND pushing the button. Here's the code for reference:
void OnTriggerEnter(Collider other)
{
if (Input.GetKeyDown("space") && other.tag == "TalkCylinder")
{
Debug.Log("Talking");
}
}
Answer by aditya007 · Nov 28, 2016 at 05:18 AM
OnTriggerEnter will be called only the time when two colliders overlap. That means, it will be next to impossible to take input at the exact frame this function is called (unless you are spamming the "space" key).
Move your code to OnTriggerStay, which will be called every frame after the colliders have made contact, and then you can check for input from the user.
void OnTriggerStay(Collider other)
{
Debug.Log("This will be called every frame");
if (Input.GetKeyDown("space") && other.tag == "TalkCylinder")
{
Debug.Log("Talking");
}
}
Please accept the answer if it solves your problem and then close the question :)
OnTriggerStay isn't necessarily updated every frame. This logic will be broken. See the other commenter.
Answer by IndieDevMans · Sep 21, 2020 at 10:10 PM
Don't use Input in OnTriggerStay. It'll give you some weird Input behaviour and so on. OnTriggerStay is runs like FixedUpdate, not each frame. Check for Input in Update instead and use OnTriggerStay to toggle a bool saying if it should be checking for Input or not.
For Example:
[SerializeField]
private bool _canPickUpCoin;
private void Update()
{
if (_canPickUpCoin)
{
if (Input.GetKeyDown(KeyCode.E))
{
_canPickUpCoin = false;
// your code
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent<Player>(out var player))
{
_canPickUpCoin = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.TryGetComponent<Player>(out var player))
{
_canPickUpCoin = false;
}
}
Your answer
Follow this Question
Related Questions
Can't click gameobject when over another trigger? 1 Answer
GameObject going into terrain. 0 Answers
Trigger to some, Collider to others 1 Answer
Problems with 2D Collision/Trigger 0 Answers
Which setup should I use for spawning? 0 Answers