- Home /
Question by
Phillipus · Dec 09, 2014 at 03:14 AM ·
c#prefabnewbiedestroy objectmissingreferenceexception
How do you destroy a prefab, but not the original object?
I've been working on a mobile game for a little while, and up until recently my game had been working correctly. For some reason, however, the enemies (which are supposed to be prefabs) have started to destroy original gameObject instead of themselves. The enemies are disappearing like they should, but when I try to create a new enemy, the console is logging:
MissingReferenceException: The object of type 'GameObject' 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.
This is the code where the enemies are destroyed:
void Update () {
time = time + Time.deltaTime;
gameObject.GetComponent<SpriteRenderer>().color = new Color(current.r, current.g, current.b, current.a * (1 - (time / 5)));
if (time >= 5) {
Destroy(gameObject);
score.GetComponent<changeSCore>().StreakEnd();
}
}
public void DestroySelf () {
Destroy(gameObject);
}
I create new enemies by calling Instantiate(enemy)
, and during runtime I can see the original enemy being removed.
I'm not that used to Unity or c#, so could you be thorough with your answer?
Thanks in advance!
Comment
Best Answer
Answer by NickvanDokkum · Dec 09, 2014 at 09:22 AM
easy fix should be
public void DestroySelf () {
Destroy(gameObject);
Destroy(this);
}