Question by
kingfrodo231 · Sep 21, 2015 at 05:44 PM ·
unity 5javascriptcrashwhile-loop
My while loop seems to crash unity
HI,
My code seems to crash unity I suspect its the while loop not being able to end any suggestions. #pragma strict
var changeCircleColor : int = 1;
var circleColor : String;
var gameState : String;
function Start ()
{
Debug.Log("The game has started");
gameState = "play";
}
function Update ()
{
while (gameState == "play")
{
ChangeCircleColor();
if(Input.GetKeyDown(KeyCode.Space))
{
gameState == "stop";
}
}
}
function ChangeCircleColor ()
{
if(changeCircleColor == 1)
{
gameObject.GetComponent.<Renderer>().material.color = Color.green;
circleColor = "green";
changeCircleColor = Random.Range(1,2);
}
if(changeCircleColor == 2)
{
gameObject.GetComponent.<Renderer>().material.color = Color.red;
circleColor = "red";
changeCircleColor = Random.Range(1,2);
}
}
Tnx Adam
Comment
Answer by matthewseaward · Sep 21, 2015 at 06:03 PM
The Update method is called every frame - your codes getting stuck in the While loop because Unity hasn't been given the chance to check for an input from a user so it won't detect that the key has been pressed. You don't need a 'While' loop it's not needed. Remove it and it should work fine :)
function Update ()
{
ChangeCircleColor();
if(Input.GetKeyDown(KeyCode.Space))
{
gameState == "stop";
}
}
And if you only want it to happen during the timeframe that the game state = play you you could use an boolean
Yes, don't use a while loop in anything other than a coroutine.