So in my game I have an object that the powerup Spawns on top of (I intend for you to have to activate it to get the powerup but for now you just walk over it, but that’s not the problem), I have it so on Start a powerup spawns, then five seconds after the powerup has worn off a new one spawn, that first cycle works fine, but after I pick up the new one, instead of spawning in the new one I get this error:
MissingReferenceException: The object of type ‘Powerup’ has been destroyed but you are still trying to >access it.
Your script should either check if it
is null or you should not destroy the
object. Powerup.Remove () (at
Assets/Scripts/Powerup/Powerup.cs:30)
Powerup.m__0 () (at
Assets/Scripts/Powerup/Powerup.cs:11)
PowerupController+c__Iterator0.MoveNext
() (at
Assets/Scripts/Powerup/PowerupController.cs:37)
UnityEngine.SetupCoroutine.InvokeMoveNext
(IEnumerator enumerator, IntPtr
returnValueAddress) (at
C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
PowerupWellController Class:
public class PowerupWellController : MonoBehaviour {
public Color color;
public GameObject powerup;
private bool powerupSpawned;
private bool powerupSpawning;
private string powerupName;
// Use this for initialization
void Start () {
powerupName = powerup.name.Substring (8, powerup.name.Length - 8);
SpawnPowerup ();
color = powerup.GetComponent<SpriteRenderer> ().color;
}
// Update is called once per frame
void Update () {
if(transform.childCount == 0){
powerupSpawned = false;
}
if(!powerupSpawned && !powerupSpawning){
powerupSpawning = true;
Debug.Log ("Spawning Powerup!");
StartCoroutine (PowerupController.CallAfterTime (SpawnPowerup, 5f));
}
}
void OnTriggerStay2D (Collider2D col){
if(col.gameObject.name == "Player"){
if(col.gameObject.GetComponent<PlayerController>().activate){
col.gameObject.GetComponent<SpriteRenderer> ().color = color;
}
}
}
private void SpawnPowerup(){
PowerupController.SpawnPowerup (powerupName, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y + 0.75f), this.transform);
powerupSpawned = true;
powerupSpawning = false;
}
}
Powerup Class:
public class Powerup : MonoBehaviour {
public Effect effect;
public void OnPickup(){
effect.action ();
effect.endAction += delegate{ Remove(); };
StartCoroutine (PowerupController.CallAfterTime(effect.endAction, effect.length));
}
void OnTriggerEnter2D(Collider2D c){
if(c.transform.tag == "Player"){
OnPickup ();
Disable ();
}
}
private void Disable(){
GetComponent<Collider2D> ().enabled = false;
GetComponent<SpriteRenderer> ().enabled = false;
}
private void Remove(){
Debug.Log ("Remove() Called!");
Destroy (gameObject);
}
}
The Remove function in the Powerup class does get called, it just doesn’t seem to destroy the second powerup after it wears off like it’s supposed to.