- Home /
How to add an IF statement based on a button click
Sorry I'm sure this is simple. I want to create an action based on a button press in a function.
At the moment I have the following but I obviously cannot nest the created AddListener function inside void Update() and I am not sure how to modify this correctly to work as an IF statement?
public bool accelerate = false;
public Button throttle;
void Start ()
{
throttle.onClick.AddListener(throttleTrue);
}
void throttleTrue()
{ accelerate = true; } // no good as is not in the loop
void Update()
{
accelerate = false; // reset button click
// Need IF section here to pull button click
If (accelerate)
{ Do stuff.. }
}
Answer by vantjac · Dec 17, 2019 at 05:45 AM
Since you're setting accelerate to false at the start of update, the if condition will never be true. Try setting accelerate to false inside the if block, after you know it's true. Or at the end of update.
Answer by ethanol3310 · Dec 17, 2019 at 05:53 AM
1) put public in front of void update. 2) Set an onclick event for the UI button and assign the Update variable.
This will not work, the update function is already being called every frame by Unity.
Answer by Rick-APL · Dec 18, 2019 at 01:22 AM
Thanks guys. So updating this, how would I create an IF condition based on the AddListener?
public bool accelerate = false;
public Button throttle;
void Start ()
{
throttle.onClick.AddListener(throttleTrue);
}
public void Update()
{
>> IF (throttleTrue) <<
accelerate = true;
{ Do stuff.. }
accelerate = false;
}
public bool accelerate = false;
public Button throttle;
void Start () {
throttle.onClick.AddListener (ThrottleClick); //onClick will only occur once
}
public void Update () {
if(accelerate){
//Do stuff
}
accelerate = false;
}
public void ThrottleCallback(){
accelerate = true;
}
This will only happen once when you click the button. If you have a throttle button, maybe you are looking for something more like this
public bool accelerate = false;
public Button throttle;
void Start () {
throttle.onPointerDown.AddListener (ThrottleDown);
throttle.onPointerUp.AddListener (ThrottleUp);
}
public void Update () {
if(accelerate){
//Do stuff
}
}
public void ThrottleDown(){
accelerate = true;
}
public void ThrottleUp(){
accelerate = false;
}