- Home /
Other
Why does Unity crash ?
when animation start Unity freeze. Also whenever I use while loop Unity freeze. This is my code
void Update()
{
while(AnimationIsPlaying("myAnimation"))
{
Debug.Log("Animation Is Playing")
}
}
bool AnimationIsPlaying(string stateName)
{
return (myAnimator.GetCurrentAnimatorStateInfo(0).IsName(stateName) &&
myAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f);
}
Answer by AaronBacon · Jul 21, 2021 at 02:11 AM
Pretty simple, that While Loop on line 3 has created an infinite loop, Update is called once per frame, and only ends once all code inside it is run. This means that on the first frame of the game, the Update gets to that while loop and cannot proceed with running the game (or indeed the Unity Editor) while the loop is still running.
if you want the Debug.Log to run every frame that the condition is true, then all you need is an if statement. Otherwise, the way to get a potentially infinite while loop to run without Locking up Unity is to use Coroutines, for example:
void Start()
{
StartCoroutine(InfiniteLoop());
}
public IEnumerator InfiniteLoop()
{
while(AnimationIsPlaying("myAnimation"))
{
Debug.Log("Animation Is Playing");
yield return null;
}
}
bool AnimationIsPlaying(string stateName)
{
return (myAnimator.GetCurrentAnimatorStateInfo(0).IsName(stateName) &&
myAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f);
}
Follow this Question
Related Questions
Why does while make Unity crash? 1 Answer
Why would this while loop crash Unity? 1 Answer
wierd infinite while loop 1 Answer
Loop crashing unity (pathfinding) 2 Answers
Script crashes Unity 1 Answer