Friday, June 3, 2011

Unity: Coroutines

So a quick description of coroutines, in the language of this utter noob. Coroutines are essentially a method/function which can be sequenced to operate independantly of the standard Update() game loop.

For (a pretty lame) example, in my last post I added a power-up which caused the player's speed to double for 5 seconds. The MonoBehaviour which triggered the power-up effect looked something like this:

// Simple Coroutine
public class PowerUp : MonoBehaviour
 // Called when the player touches the power-up
 void OnTriggerEnter(Collider activator)
  StartCoroutine(PowerUpSpeed(2.0f, 5.0f));

 // The Coroutine which handles the power-up
 IEnumerator PowerUpSpeed(float multiplier, float duration)
  Debug.Log("Powering up the Player!");
  Player.Instance.MovementSpeed = Player.Instance.MovementSpeed * multiplier;
  // The next line causes this method to pause execution for 'duration' seconds
  yield return new WaitForSeconds(duration);
  Debug.Log("Powering down the Player! Aw!");
  Player.Instance.MovementSpeed = Player.Instance.DefaultSpeed;

So in this example, the OnTrigger() event (which is called automatically by Unity) in turn starts the coroutine PowerUpSpeed(). The coroutine prints "Powering up the Player!" to the console, then increases the player's speed. Then the yield statement is used to pause the coroutine until the yield's specified method returns. In this case, the method is WaitForSeconds(), which as the name suggests, waits for the specified number of seconds before returning. After the WaitForSeconds() method returns, the coroutine prints "Powering down the Player! Aw!" to the console, and the player's speed is reset to the default value.

Coroutines ROCK! I also use a Coroutine to control the Portal sequence: fade to black, teleport the player, teleport the camera, fade up from black.


StartCoroutine(GoToWork(8.0f * 60.0f * 60.0f));

No comments:

Post a Comment