What is a game without power-ups? Not much of a game. So how do you create power-ups and make sure they only last for a while? Let’s have a closer look at power-ups, how to provide them and then limit their duration in this article.
What are Power-Ups?
A power-up is an extra ability that a player can obtain to assist them in playing the game. They are usually an event that a player triggers during gameplay. They can be triggered after inflicting an amount of damage or simply being something a player collects. What the extra ability will be and its duration will depend on the game designer and programmer.
This article will cover how to enable a collectable power-up for a player and limit its duration during gameplay.
Spawning Collectable Power-Ups to a Player
For this article, we will deliver power-ups to the player at a random interval. Within our Spawn Manager script, we create a Coroutine to instantiate the power-ups on a random interval between three seconds and nine seconds.
IEnumerator SpawnPowerUpRoutine()
{
while (_stopSpawning == false)
{
GameObject powerup = Instantiate(_powerUpPrefab, new Vector3(Random.Range(-2.3f, 2.3f), 8, 0), Quaternion.identity);
yield return new WaitForSeconds(Random.Range(3, 10));
}
}
Although we have specified a random range between 3 and 10 seconds because we are using whole numbers, the largest random number is 9 seconds.
In void Start, the Coroutine must be started for the power-ups to be spawned.
StartCoroutine(SpawnPowerUpRoutine());
Limiting the duration of the Power-Ups
So how do we limit the duration of the power-up that the player collected? You may not want them to continue to use the power-up forever. Back on the Player script, before the void Start function, we create a variable of type bool to determine if the power-up is active or not.
private bool _isPowerUpActive;
Let’s create the Coroutine to limit the duration of the power-up for 5 seconds.
IEnumerator TripleShotInactive()
{
while (_isPowerUpActive == true)
{
yield return new WaitForSeconds(5);
_isPowerUpActive = false;
}
}
We now create a public function to activate the power-up and start the Coroutine to limit its duration.
public void PowerUp()
{
_isPowerUpActive = true;
StartCoroutine(PowerUpActive());
}
The final step is for the associated Power-Up script to detect that the player has collected it, enable the power-up and destroy itself.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == “Player”)
{
Player player = other.transform.GetComponent<Player>();
if (player != null)
{
player.PowerUp();
}
Destroy(this.gameObject);
}
}
I hope this article has helped you create and limit power-ups in your game. Let me know what other articles you would like me to write that can help you.