- Home /
How do I allow my function to run only once at a time?
So in my program I have a button that when I press will generate a series of random numbers and output it into the UI. I got my random number generator working but I could not figure out a way to not let the the function run only one at a time.
I need it so that when I press the button (Roll()), the button will not be interactable for the time the numbers are being generated, then when the function finishes performing, the button becomes interactable again.
The problem for me now is I don't know while my while statement is not making the button not interactable and so I can press my button many times and the function will just run multiple times at a time cause lots of random numbers to be displayed which is what I don't want.
Thank you for any help in advance.
private int RanNum;
private bool Rolling = false;
public Text RolledNum;
public Text HasBeenRolled;
public Transform RollButton;
void Start () {
RollButton.GetComponent<Button> ().interactable = true;
}
void NumRoll(){
RanNum = Random.Range (1, 15);
RolledNum.text = RanNum.ToString ();
}
void RepeatRoll(){
InvokeRepeating ("NumRoll", 0, 0.3f);
Rolling = true;
while (Rolling == true) {
RollButton.GetComponent<Button> ().interactable = false;
}
}
public void Roll(){
RepeatRoll ();
}
Answer by MrRightclick · Jul 18, 2016 at 01:36 PM
You could use a coroutine and let it run in a while(true) loop until you have rolled all the numbers, or then just put a simple timer function on the button like so (untested code, but you get the gist):
public void ButtonPressed () {
button.interactable = false;
Invoke("ReActivateButton", 2);
}
public void ReActivateButton () {
button.interactable = true;
}
Hey, thank you so much! It's doing what I want it to now but I'm not sure if it's the most efficient way but anyways it works! I still don't know why my previous method does not though... weird. Thank you!
Glad it worked. The only thing I'd be worried about (if the randomization could take time depending on the platform) is the button beco$$anonymous$$g active before the timer runs out.
You should also check coroutines if you aren't familiar with them yet. Very useful, very flexible, and I think they would work wonders here: https://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.StartCoroutine.html
Your answer
Follow this Question
Related Questions
Changes in variables from function triggered by editor script during edit mode are not applied. 2 Answers
Jumping on moving platforms problem c# 1 Answer
OnSelect and OnPointerEnter work in one script but not another on the same object 2 Answers
The variable has not been assigned - but it has 1 Answer
Create GUI based on an array 2 Answers