Bad Response Time for Input.GetKeyDown
So I've got a scene set up where a character walks over to a boundary zone and if they're within that zone (checked by OnTriggerStay) the player can push "e" (checked by Input.GetKeyDown)to animate a button pushing down (just a basic little thing with a cylinder moving down). The problem is, Unity is only recognizing me hitting "e" approximately 1/3 of the time. If I stand still and rapidly press the button, it will eventually go. Is there any way to tell by looking at the code below what is causing this to take so long? Any assistance would be greatly appreciated! :-)
TriggerBox (This is attached to the boundary zone - a child of the button prefab)
public class TriggerBox : MonoBehaviour
{
public bool isActive = false;
void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player")) //Compare if the entering Collider belongs to "Player"
{
if (Input.GetKeyDown("e")) //If the above is true and the player selects "e", continue
{
isActive = true; //gives a point of interaction between TriggerBox and ButtonPush
Debug.Log("isActive has been set to true");
}
}
}
}
ButtonPush (the script that is attached to the actual button)
public class ButtonPush : MonoBehaviour {
public GameObject otherGameObject;
private TriggerBox triggerBox;
private Animator thisButton;
// Update is called once per frame
void Start ()
{
triggerBox = otherGameObject.GetComponent<TriggerBox>();
thisButton = GetComponent<Animator>();
}
void Update()
{
//This is designed to check once per frame if the boundary
//zone's bool "isActive" is true - if so, it will run the
//code to animate the button, then set the bool to false
if (triggerBox.isActive == true)
{
thisButton.SetBool("buttonAnimPlay", true);
Debug.Log("Animation has played.");
triggerBox.isActive = false;
Debug.Log("isActive has been set to false");
}
}
void ButtonEnd() //Animation Event
{
thisButton.SetBool("buttonAnimPlay", false);
}
}
Answer by Positive7 · Sep 10, 2015 at 02:38 PM
Input should be called in Update() or Corutines only see doc : http://docs.unity3d.com/ScriptReference/Input.html
OnTrigger... is Physics based and its not getting called every frame. Similar to FixedUpdate()
if I'm not mistaking that's why your button press is not registered.
Set up a bool and set it true in OnTriggerStay()
Then In Update check if keydownn && bool is true e.g.:
bool mybool;
void OnTriggerStay(Collider other)
{
if (other.CompareTag ("Player")) {
mybool = true;
}
}
void Update(){
if (Input.GetKeyDown ("e") && mybool) {
isActive = true;
}
}
Your answer
Follow this Question
Related Questions
Animation won't stop (Solved) 2 Answers
On-click and trigger animation c# 1 Answer
SetBool animation state based on direction object is moving 0 Answers
Referenced Bool is not updating 1 Answer