- Home /
UI Buttons to work continuously when pressed and held for sometime
Hi, so I have a UI Button which when pressed activates a FireNow() function, which fires a bullet. Now I want to fire continuously, so I have added OnPointerDownHandler and OnPointerUpHandler to my code. But I am not able to access these functions in my FireNow function. This is the code. How do I access them in FireNow(). The Shoot() function performs the real shooting.
public void OnPointerDown(PointerEventData eventData) { ispressed = true; }
public void OnPointerUp(PointerEventData eventData)
{
ispressed = false;
}
// Update is called once per frame
public void FireNow () {
if (isreloading)
return; //if reloading then don't go ahead
if(currentammo<=0) //if we have no ammo
{
StartCoroutine(Reload()); //reloading done here through coroutine
return; //don't go ahead in this function
}
if (Time.time >=nextTimeToFire && ispressed) //Input.GetButton("Fire1") and Time.time adds real time
{
Shoot(); //function to shoot when left mouse button is clicked
nextTimeToFire = Time.time + 1f / 11f; //shows which is the next time to fire
}
}
Answer by Hellium · Aug 23, 2018 at 09:57 PM
Simply call your function in Update
while isPressed == true
public void OnPointerDown(PointerEventData eventData)
{
ispressed = true;
}
public void OnPointerUp(PointerEventData eventData)
{
ispressed = false;
}
private void Update()
{
if( isPressed ) FireNow();
}
// Update is called once per frame
public void FireNow () {
if (isreloading)
return; //if reloading then don't go ahead
if(currentammo<=0) //if we have no ammo
{
StartCoroutine(Reload()); //reloading done here through coroutine
return; //don't go ahead in this function
}
if (Time.time >= nextTimeToFire) //Input.GetButton("Fire1") and Time.time adds real time
{
Shoot(); //function to shoot when left mouse button is clicked
nextTimeToFire = Time.time + 1f / 11f; //shows which is the next time to fire
}
}
Thank you for answering but now it is not firing a single time!! Where I am missing?? I made Update function public and passed its reference in my Button.
No no, you don't have to pass the Update
function to the onClick
button.
This script must be attached to the button. Remove every listener to the onClick
event. Update
, OnPointerDown
and OnPointerUp
will be called automatically.
Ahh that's where I was missing!! Thank You so much, it's working fine now. I was wondering since days and finally you saved me!