- Home /
While loop not updating
Hello, I am attempting to make an object grown and then shrink back down and disappear. I need to do this through the use of a UI button. I have a while loop, which should allow the object to grow, but unfortunately, it is not. Any help will be appreciated.
public void Activate ()
{
while (scale < maxSize) {
gameObject.transform.localScale = Vector3.one * scale;
scale += growthRate * Time.deltaTime;
}
scale = 0.01f;
gameObject.transform.localScale = Vector3.one * scale;
gameObject.SetActive (false);
myButton.interactable = false;
}
Answer by DoTA_KAMIKADzE · May 24, 2015 at 02:05 PM
Your whole while loop is executed between 2 frames (e.g. FrameX => your whole Activate function to end => FrameX+1). So sure thing you won't notice anything if your scale was 0.01f before you run that function.
As instead you should leave some gaps in time between updates of your "scale". It can be achieved by updating values inside continuously running functions like Update, FixedUpdate, etc. With smallest changes to code you can do that via Coroutine, and it will look ~like that:
public void Activate()
{
StartCoroutine(hereWeGo());
}
IEnumerator hereWeGo()
{
while (scale < maxSize)
{
gameObject.transform.localScale = Vector3.one * scale;
scale += growthRate * Time.deltaTime;
yield return new WaitForSeconds(0.5f);//wait time between scale updates
}
scale = 0.01f;
gameObject.transform.localScale = Vector3.one * scale;
gameObject.SetActive(false);
myButton.interactable = false;
}
You can call that coroutine from any other place in your code as well.
P.S. Also NOTE that in case of coroutine you shouldn't really use Time.deltaTime but some constant instead. Time.deltaTime is more suitable for Update function.
Your answer
Follow this Question
Related Questions
Dynamically set the sprite of a button in loop 0 Answers
Assigning a function with a parameter to buttons in for loop with a temp variable 1 Answer
Issue with spawning buttons and assigning listeners 1 Answer
How to change the Object on UI button 1 Answer
UI button pressed animation not playing directly after entering 2 Answers