- Home /
Yield Not Working - While Loop
Hello,
I'm completely confused in why my while loop wont work, all its suppose to do is change my object material from on to another, over and over again.
function Start(){
AnimateElectic();
}
function AnimateElectic(){
print("Animating Shock!");
while(true){
//yield WaitForSeconds(1);//Random.Range(0.0, 5.0));
bat.renderer.material = levelTextures[3];
print("On");
//electric = true;
//yield WaitForSeconds(1);//Random.Range(0.0, 5.0));
yield WaitForSeconds(0.5);
//yield WaitForSeconds(1);//Random.Range(0.0, 0.8));
bat.renderer.material = levelTextures[2];
print("Off");
//electric = false;
//yield WaitForSeconds(1);//Random.Range(0.0, 0.8));
yield WaitForSeconds(0.5);
}
//animateEffect = false;
}
But it just doesn't work, it does the first section - so it changes the material to levelTexture[3], prints the 'On', but seems to fail at the yield? I've used loads the loops before, and yet this one doesn't seem to work? Am I being stupid here?
EDIT:
I forgot to add that the object is Instantiated at a certain point. If I start the game with the object already in the scene, active, then the loop works. But when I instantiate it at a later stage in the game, it only does the first section, once.
Thanks
Answer by Kryptos · Aug 16, 2012 at 02:13 PM
Start is only called once. So if your object is active, then you deactivate it then you activate it again, Start will not be called again.
Consider calling the coroutine in OnEnable() instead of Start().
Ah wow, I had no idea there was such a thing as 'OnEnable'. Thanks!
These two pages of the documentation can be really useful:
Answer by shinriyo_twitter · Apr 25, 2013 at 06:18 PM
UnityScript is bad, C# is better.UnityScript is redundancy
Answer by SolidSnake · Aug 16, 2012 at 01:39 PM
Do you get an error log?...
I am coding mostly in C#, but don't you need to call the function like this in JavaScript:
StartCoroutine(AnimateElectic());
I get no error log, and like I said, it works - but only when the object is already active in the game. But thats not what I want, its already in the scene, but not active until a certain game trigger.
and by not active you mean not instantiated? or simply you are setting active property to false?
Your answer
Follow this Question
Related Questions
Simple rotation script. (loop) 3 Answers
Definition of Script.function() depends on Script.function()... 3 Answers
A delay/yield/wait function for function Update? 6 Answers
while loop not looping 2 Answers
Loop animation with a wait in between 3 Answers