Ive been stuck for 2 days now trying to find this answer.
I made a game where you can trip shrooms, but when you eat them you instantly trip and all the effects happen at once-which isnt realistic. Heres just a simple script showing what Im trying to do:
var rotateObj1 : GameObject;
var rotateObj2 : GameObject;
var rotateObj3 : GameObject;
var theSun : GameObject;
function Update () {
yield WaitForSeconds(10);
rotateObj1.transform.rotation += 1;
rotateObj2.transform.rotation += 1;
rotateObj3.transform.rotation += 1;
yield WaitForSeconds(5);
theSun.light.range -= 20;
yield WaitForSeconds(15);
//next effect and so on...
}
Just put the effects code in a function of its own and call that in update. (with a check if it should be called or not.)
Lets see…I’l just give you an example of how I recently used mine and you can modify it to how you want. I find it more learning if you adapt it to your own than getting the answer directly.
IEnumerator Wait(){
Debug.Log ("about to yield return WaitForSeconds(5)");
yield return new WaitForSeconds(5);
Destroy(gameObject);
Debug.Log("finished");
}
void OnTriggerEnter2D (Collider2D other) {
if(lives == 0){
ren.sprite = deadNinja;
death = true;
//The yield and waitforseconds in wait() waits for the appointed time before
//running wait(). In the meantime the rest of the function runs.
//This is the reason why Destroy is in wait() since we want to wait
//before we destroy the ninja allowing the user to see the deadNinja
StartCoroutine(Wait());
Debug.log("This will be run before the Wait() funtion");
}
}
In this code, everything will run when something hits the object which has this script. I had it in my ninja. So when he’s hit and he got zero life, it begins:
- The sprite is changed.
- dead is set to true
- StartCorutine begins
- goes into wait and print out the first message: “about to yield return WaitForSeconds(5)”
- look at yield and goes back to the OnTriggerEnter2D function
- Runs the message “This will run before the Wait() function” message
- after doing with the whole OnTriggerEnter2D, it goes back to the Wait() function
- after the 5 seconds are gone
- Destroys the ninja
- Runs the message “finished”.
That’s how I used mine and it works. I hope the example makes sense to you,and the same with me running through it. I don’t think you can just run WaitForSeconds(5) just like that without the magical incantation “yield return new” before it but I’m no unity wiz so I could be wrong.
The reason that it does not work is because you cannot have a WaitForSeconds event in a pre-made function, that means that you have to make a function that you call in and in that function you have to have those WaitForSeconds events and then it will work, I promise.
Like this:
function Start () {
Apply_Effects();
}
function Apply_Effects () {
yield WaitForSeconds(<insertTimeHere>);
<do something here>
yield WaitForSeconds(<insertTimeHere>);
<do something here
}