- Home /
Why does while make Unity crash?
Hi there,
About a week ago I knew nothing about Unity or even programming in any language so be easy on me..(=
I'm playing around with Unity and trying to get a Spine animation to stand idle when no key is pressed and to play a different run animation and move along the x axis when "right" or "left" are pressed.
I think I got the moving part right, in this code I tried disabling the idle animation and enabled the run animation whenever I press "right" or "left", for some reason Unity crashes every time I click play.
Thanks in advance!
using UnityEngine; using System.Collections; public class movePlayer : MonoBehaviour { public float speed ; private SkeletonAnimation run; private SkeletonComponent idle; void Awake () { run = GetComponent<SkeletonAnimation>(); idle = GetComponent<SkeletonComponent>(); } void Update() { float translation = Input.GetAxis ("Horizontal") * speed; translation *= Time.deltaTime; transform.Translate (translation, 0, 0); bool held = Input.GetButton("Jump"); while(held) { idle.enabled = false; run.enabled = true; } } }
Answer by Bunny83 · Nov 17, 2013 at 03:32 PM
It doesn't actually crash, it just does what you told your PC to do. Unity uses a single thread for scripting. So your PC happily is looping your two lines of code that are inside your while loop as long as "held" is true. Since held isn't changed inside the while loop it will never leave the loop.
Before you try something like this:
while(held)
{
held = Input.GetButton("Jump");
idle.enabled = false;
run.enabled = true;
}
That won't work either. The input (and everything else Unity does) is only updated once per frame. If you don't let Unity finish the current frame (with an endless while loop), nothing will be updated.
You might want something like this:
bool held = Input.GetButton("Jump");
if(held)
{
idle.enabled = false;
run.enabled = true;
}
else
{
idle.enabled = true;
run.enabled = false;
}
For some reason the run.enabled would not work but I think there is a better way to do this, ins$$anonymous$$d of having 2 animation scripts would there be a possibility to address the drop down within one?
This is how the script I imported from Spine looks:
How would I know the correct code for changing stuff in inspector within the code?
Thank you so much for the answer! Really helpful and understood!
Your answer
![](https://koobas.hobune.stream/wayback/20220613122056im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
wierd infinite while loop 1 Answer
Why does Unity crash ? 1 Answer
Why would this while loop crash Unity? 1 Answer
Massive memory usage during compile time 0 Answers
Unity 4.2.0f4 Crash. Why? 1 Answer