Determining How Long Powerup Effects Should Last
Objective: Learn how to set a timer for our Powerups.
Now we have our Powerup system, but they last indefinitely. How do we implement a system to make sure that our Powerups lasts only a couple of seconds ?
Well, we know pretty well that Coroutines are a great way to manipulate time within a method.
This is a very simple solution when handling timeframes in Unity. We can simply use a Coroutine that will simply wait for a specific amount of time, in this case 5 seconds, and then we can execute our code for turning our TripleShot off.
Now all we need is a public method that starts the Coroutine, and when colliding with our Player, we call that method instead.
public void EnableTripleShot()
{
StartCoroutine(EnableDurationPowerUpRoutine());
}
And in our Powerup GameObject, we can simply call this method when we collide with our player, granting him our much loved TripleShot.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
if (player != null)
player.EnableTripleShot(_duration);
Destroy(gameObject);
}
}
Now we set our Powerup to call the method on the player, and then Destroy itself. When the method its called, it will start the Coroutine and activate our TripleShot. The program will Yield and wait for the specific amount of time we gave, and then deactivate our TripleShot.
private IEnumerator EnableDurationPowerUpRoutine()
{
_isTripleShotOn = true;
yield return new WaitForSeconds(5f);;
_isTripleShotOn = false;
}