- Home /
How to simulate GetKeyDown for a UI button
So basically I have this problem
if (jumpButton.GetComponent<PointerListener>().pressed && m_Grounded)
{
jump = true;
}
/*
some code
*/
if (jump && m_Grounded) //&& m_Anim.GetBool("Ground"))
{
m_Grounded = false;
//m_Anim.SetBool("Ground", false);
m_Rigidbody2D.AddForce(transform.up * m_JumpForce);
}
and JumpButton script is
public class PointerListener : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public bool pressed = false;
void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
{
pressed = true;
}
void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
{
pressed = false;
}
}
In the first one if I use GetKeyDown("Space") it jumps as I wish,but if I use what I listed above it jumps 3 or 4 times upper
Answer by invo1 · Jan 03, 2018 at 04:35 PM
I figured it out,i called a courutine and I yield return new WaitForEndOfFrame();
This feels very heavy duty answer for your question. Are you actually using the button UI ? Or dose this 1 extra line of code also work if (jumpButton.GetComponent().pressed && m_Grounded) { jump = true; jumpButton.GetComponent().pressed = false; } either way a fix is fix :D
Answer by OneCept-Games · Jan 03, 2018 at 03:57 PM
Unity may register several OnPointerDown events until you again lift your finger. Try to add a counter and debug it. Also try moving AddForce method to FixedUpdate() if not already there.
it's already there,and I tried with courutine that waits 0.01 seconds and the problem still persists and now with a counter and still no
Your answer
Follow this Question
Related Questions
My function is called twice on single click 2 Answers
Creating a Tooltip when hovering over a UI Button? 3 Answers
How do I asign this script to a button successfully? 1 Answer
UI Buttons to work continuously when pressed and held for sometime 1 Answer
UI Button event triggers don't work on mobile but work in eaditor? 0 Answers