Hi Does this yield statement work within this script? Is there another way of expressing this? Code (csharp): function OnCollisionEnter () { yield WaitForSeconds(5.0); Application.LoadLevel("AtlantisAug2"); } Thanks By the way I also have this on the same game object Code (csharp): function Update() { transform.Translate(0, 0 * Time.deltaTime, 1.5); }
Why are you multiplying 0 with Time.deltaTime and not the 1.5? The multiplcation with zero seems pointless and not multiplying the z axis makes your script framerate dependent. Didn't you mean to say: Code (csharp): function Update() { transform.Translate(0, 0, 1.5 * Time.deltaTime); }
So, apparently you're waiting 5 seconds after the object collides with something, and then reloading the level? I'm assuming you're going to have some explosion effect or something...just waiting 5 seconds would be boring as I'm sure you know. But even with an explosion, 5 seconds is too long. Seriously, when you've crashed and you're itching to get back into the action, you don't want to sit there for 5 whole seconds, no matter how spectacular your demise might be. A good alternative might be not using WaitForSeconds at all, and doing a 5 second timer using Time.time instead, during which you poll, say, the fire button, so the player can respawn immediately if he chooses. But that's just 25 years of videogaming talking. The other problem I see is that you're specifying the name of the level explicitly when you do LoadLevel. This means you'd have to save a different version of the script for every level. Expose that as a variable instead...that way you don't have to touch the script when you're done with it, and you can just enter the name with the Inspector for each level. ...Unless, of course, you're only ever going to have 1 level, in which case, never mind about that bit. --Eric
Yield only works in coroutines (and, I believe, methods called from coroutines). I'm almost certain that OnCollisionEnter() is not called as a coroutine, and therefore yield can't work there. Instead, you should use Invoke() to call another method after five seconds, like this: Code (csharp): function OnCollisionEnter() { Invoke("LoadNextLevel", 5.0); } function LoadNextLevel() { Application.LoadLevel("AtlantisAug2"); }
Actually thats not the case. All event functions are made to also work as coroutines. (I think that was added with Unity 1.2) So the code targos posted works and it is also a very elegant way to do it. Code (csharp): function OnCollisionEnter () { yield WaitForSeconds(5.0); Application.LoadLevel("AtlantisAug2"); }
Now you tell me. Does it say that in the documentation somewhere? I feel like there are quite a few things which would save me a lot of time but which I've overlooked because they were silently added during an update....