Everyone who uses Unity3D should know about great thing like
StartCoroutine. For everybody else - it's the easy way to implement some logic that should be executed during game without pausing it.
OK, time for code.
Coroutinemanager
public class CoroutinesManager
{
private readonly List<IEnumerator> _coroutines = new List<IEnumerator> ();
public void Start(IEnumerator enumerator)
{
_coroutines.Add (enumerator);
}
public void Update()
{
for (int i = _coroutines.Count - 1; i >= 0; i--)
{
IEnumerator enumerator = _coroutines[i];
if(!enumerator.MoveNext())
_coroutines.RemoveAt(i);
}
}
}
Example: change color in time
public class Game1 : Game
{
readonly CoroutinesManager manager = new CoroutinesManager();
...
protected override void Update (GameTime gameTime)
{
...
if (Keyboard.GetState ().IsKeyDown (Keys.Space))
manager.Start (ChangeBackgroundColor(gameTime, 10.0f));
manager.Update();
...
}
private IEnumerator ChangeBackgroundColor(GameTime gameTime, float duration)
{
float timer = 0;
while(timer < duration)
{
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
backgroundColor = Color.Lerp(Color.CornflowerBlue, Color.Green, timer / duration);
yield return null;
}
}
}