- Home /
Input trigger doesn't work
Hi everyone,
I'm new to unity (and javascript ^^) and I can't find a solution to my problem.
Here is the problem: I have a script which is working, but when I want to add interactivity with Input.GetButton, nothing happens.
Here is my script:
function OnTriggerEnter(myTrigger : Collider) {
Debug.Log("Hi");
if(myTrigger.gameObject.name == "Sphere" && Input.GetButtonUp("Retreat")){
Debug.Log("follow");
gameObject.GetComponent( IA_Follow_Player ).enabled = true;
}
}
function OnTriggerExit(myTrigger : Collider) {
if(myTrigger.gameObject.name == "Sphere"){
gameObject.GetComponent( IA_Follow_Player ).enabled = false;
Debug.Log("Stun");
}
}
Without " && Input.GetButtonUp("Retreat") " (first if statement), everything is working perfectely. But when I add it, I don't have any error on the console and I can read the messages "Hi" and "Stun" from the console. Unfortunately, I can't read "Follow" and my script "IA_Follow_Player" doesn't play.
Basically, I just want my script "IA_Follow_Player" to execute if the gameObject my script is attached to is colliding with "Sphere" AND if I press a key.
(I also tried with Input.GetButton("Retreat") / Input.GetButtonDown("Retreat") / Input.GetKey(1) / Input.GetKeyUp(1) / Input.GetKeyDown(1), and I named in the input manager a "Retreat" input. I also tried many keys to be sure that it was not from my keyboard).
Does anyone have a clue ?
Thanks a lot.
Answer by MrSteve1 · Apr 22, 2013 at 08:11 AM
If you want "interactivity" you will need OnTriggerStay or a different function. Here's my suggestion.
var follow : boolean = false
function Update()
{
if(Input.GetButtonUp("Retreat")){
if(follow){//<-- same as if(follow == true)
gameObject.GetComponent( IA_Follow_Player ).enabled = true;
}
}
}
function OnTriggerEnter(myTrigger : Collider) {
Debug.Log("Hi");
if(myTrigger.gameObject.name == "Sphere"{
Debug.Log("follow");
follow = true;
}
}
function OnTriggerExit(myTrigger : Collider) {
if(myTrigger.gameObject.name == "Sphere"){
gameObject.GetComponent( IA_Follow_Player ).enabled = false;
follow = false;
Debug.Log("Stun");
}
}
It works perfectly. Thanks a lot man, I owe you a beer : )
Thanks man. I drink London Pride or Brooklyn Brewery! I would encourage you to accept this as a correct answer in case anyone else has the same issue.
Answer by AlucardJay · Apr 22, 2013 at 07:56 AM
The problem is you are trying to detect a key event in the exact same frame as a trigger event. Unless the player has amazing timing or pure luck, this will never happen. The OnTriggerEnter event only happens for a single frame, and so does Input.GetButtonUp. You need to rethink what you are trying to do.
Oh. I see. I thought that OnTriggerEvent was checking each frame.
Thanks a lot for the quick answer : )
Your answer
![](https://koobas.hobune.stream/wayback/20220613100808im_/https://answers.unity.com/themes/thub/images/avi.jpg)