I am using coroutines to manage cooldowns for powerups in my game. When the player collides with a powerup they will get the effect and a cooldown will start so they can't use it again for a certain amount of time.
I am using coroutines to manage these cooldowns - setting the gameObject to false, waiting for the cooldown, then setting the gameObject back to true.
My code:
IEnumerator RespawnTime ()
{
gameObject.SetActive(false);
Debug.Log("disabled");
yield return new WaitForSeconds(3f);
gameObject.SetActive(true);
Debug.Log("enabled");
}
private void OnCollisionEnter2D (Collision2D collision)
{
// Health stuff goes in here.
Debug.Log("Health regen!");
// Start cooldown
StartCoroutine(RespawnTime());
}
However, the gameObject is never activated again once disabled. I don't think the problem is with the yield as commenting out the SetActive statements results in both debug messages being displayed at the correct times.
Edit:
Sorry, I didn't clarify. I know coroutines don't run on disabled GameObjects. I made a PowerUpManager script and it didn't work. Code:
In the PowerUp script, in the OnCollisionEnter2D method
StartCoroutines(PowerUpManager.RespawnTime(gameObject))
In the PowerUpManager script
public static IEnumerator RespawnTime(GameObject powerUp)
{
powerUp.SetActive(false);
yield return new WaitForSeconds(3f);
powerUp.SetActive(true);
}
coroutinesfor disabled objects are disabled as well. You have to run this coroutine in other gameobject. - R2RT