Ved Sarkar Ved Sarkar - 1 year ago 71
C# Question

Run code when button is held down

I am new to unity and building a game, I use 2 buttons (IncreaseButton, DecreaseButton) the problem I have is that the button callback functions are only called once, when the user clicks on the button but not when the button is held down. How can I make the button to be called repeatedly when held down?


public void IncreaseBPM()
if (speed < 12)
speed += 0.05f;
bpmText.GetComponent<BeatTextControl> ().beats += 1;
PlayerPrefs.SetFloat ("savedBPM", speed);

public void DecreaseBPM()
if (speed > 1.5)
speed -= 0.05f;
bpmText.GetComponent<BeatTextControl> ().beats -= 1;
PlayerPrefs.SetFloat ("savedBPM", speed);

Answer Source

okay so firstly you create 2 booleans:

bool increase = false;
bool decrease = false;

then you set them inside the functions

public void WhenButtonClicked()
    { increase = true; }
public void WhenOtherButtonClicked()
    { decrease = true; }

Then in the update function inside the same file you check:

Void update(){
   If(increase){ IncreaseBPM(); }
   Else if(decrease){ DecreaseBPM(); } 

About when the button gets released, i found a simple answer:

Add an Event Trigger component to your button (In the event menu). From there you can add a listener for OnPointerUp. Treat it just the same as OnClick.

And create 2 other functions that set increase and decrease to false !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download