Infinite power! And how to prevent it — A quick guide to setting the duration to a powerup in Unity
How boring would Mario be if the star powerup lasted the entire game? Can you appreciate a speed boost if you can use it an infinite number of times?
Giving a player a reward for better weapons is great, but the feeling of being overpowered can really reduce enjoyment in your game. This is where we can use coroutines to turn a powerup on and off.
In our example, we are going to focus on our triple shot power-up. When we collect the powerup at the moment we have our triple shot activated forever. That is way too overpowered. Let's set up a duration system. I’m going to use a period of about 5 seconds but leave it editable in the inspector.
What we need to do is create our coroutine which will activate our powerup and then deactivate it after our set duration.
Now we can test our script.
What you may notice is that the second powerup did not last as long as the first. We discuss this in my previous article on coroutines. What we need to do is create a variable to holds our coroutine and sets it to null when the routine is not running.
To stop our instance of the coroutine and then start a new one we need to check our reference to see if the routine is running. Then when we run the routine set it to null once it is complete.
Now if we test our script we should get our intended results.