Ved Sarkar Ved Sarkar - 3 months ago 9
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?

Code

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

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: http://answers.unity3d.com/questions/843319/46-gui-button-onrelease.html

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 !

Comments