Hi @Kubilay,
You’re welcome.
Looking at your approach, I’d probably aim to consider the separation of concerns. At the moment your “collectable” knows not only which power-up it is going to deliver, but it also wants to control that power-up’s behaviour.
I would probably start by creating a PlayerShield class/script, perhaps pop it in a “Power-Ups” folder.
This class would literally just handle the behaviour related to the shield itself, so, you could either move your coroutine code into it and then call it from the Start
method, or, if you don’t need as much control over what happens when, e.g. you just want to destroy the shield GameObject after a period of time you could use Unity’s overloaded Destroy
method;
// destroys the gameobject the script is attached to after 10 seconds
Destroy(gameObject, 10f);
So, the PlayerShield script might look like this;
using UnityEngine;
public class PlayerShield : MonoBehaviour
{
private void Start()
{
Destroy(gameObject, 10f);
}
}
If you want more control over the behaviour, then stick with the coroutine approach and call that from the Start
method;
using System.Collections;
using UnityEngine;
public class PlayerShield : MonoBehaviour
{
private void Start()
{
StartCoroutine(SelfDestruct());
}
private IEnumerator SelfDestruct()
{
// do coroutine stuff in here
}
}
In all cases you might want to consider a few thing like;
- any audio sfx when the shield activates/de-activates
- any particle effects to start/stop
- a configurable/random duration for the power-up
The PlayerShield script would be attached to your shield prefab. When you instantiate it from the code in your “collectable”, it’s Start
method will fire, as such you have now separated the behaviour of what the shield will do from the code in your “collectable”.
This will then allow you to just Destroy
the “collectable” game object after instantiating the shield prefab.
The approach above would also allow you to extend your power-up functionality, your “collectable” could effectively randomise which power-up a player may get, you’d have a separate script for each power-up type, attached to the appropriate prefab. Your code above to instantiate would be largely the same, you’d just randomise a number, and then choose the appropriate prefab based on the value.
Hope the above is of use.
See also;