I have a simple game in which the player can collect power-ups. Each power-up gives the player a temporary advantage for several seconds. The power-up should disappear immediately after the player collects it.
My current implementation of the power-up logic is:
[SerializeField] float duration;
private void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "Player") {
StartCoroutine(GiveTemporaryPowerup(other.gameObject));
Destroy(gameObject);
}
}
private IEnumerator GiveTemporaryPowerup(GameObject gameObject) {
gameObject.ActivatePowerupFunction();
yield return new WaitForSeconds(duration);
gameObject.DeactivatePowerupFunction();
}
This does not work: the powerup is activated but not deactivated. Deactivation does work when I remove the line "Destroy(gameObject)". However, without this line the player can collect the same powerup several times, which I want to avoid.
I tried to put the coroutine on a component attached to the player object (rather than the power-up object), but this did not solve the problem - deactivate was not called. Here is the updated code on the power-up:
private void OnTriggerEnter2D(Collider2D other) {
if (other.tag == "Player") {
var playerComponent = other.gameObject.GetComponent<Player>();
StartCoroutine(playerComponent.GiveTemporaryPowerup(duration));
Destroy(gameObject);
}
}
And the code on the Player component:
public IEnumerator GiveTemporaryPowerup(float duration) {
ActivatePowerupFunction();
yield return new WaitForSeconds(duration);
DeactivatePowerupFunction();
}
What is the correct way to implement this?