How to fix MissingReferenceException when a GameObject gets destroyed from an array?
Got this code from a free turret asset. I've got 5 turrets set as enemies, my problem is every time one turret or all turrets get destroyed it throws this MissingReferenceException warning on the console. Any idea on how to fix this, thanks in advance.
public GameObject[] turrets;
public virtual void Update(){
foreach(GameObject turret in (this.turrets as GameObject[]))
turret.SendMessage("Target", this.transform.position);
}
Answer by Larry-Dietz · Dec 05, 2019 at 02:40 PM
Try checking that it still exists before sending the message. Something like this.
public virtual void Update()
{
foreach(GameObject turret in (this.turrets as GameObject[]))
if(turret != null)
turret.SendMessage("Target", this.transform.position);
}
It worked, Thank you so much Larry. One last thing is it also possible to disAble or destroy the gameObject that this script is attached to if the turret is null?
try this...
public virtual void Update()
{
if(turrets.Length==0)
destroy(gameObject)
else
foreach(GameObject turret in (this.turrets as GameObject[]))
if(turret != null)
turret.Send$$anonymous$$essage("Target", this.transform.position);
}
Glad I was able to help.
Unfortunately it did not work, didn't destroyed the gameObject, by the way I had to add ; after destroy(gameObject) from your recent reply. Anyway I'm happy with first code you provided, I think I'll stick to that as long as there is no warning on the console I'm fine. Thanks again.
Sorry about the missing ;
I should have anticipated that this wouldn't work, since when the turrets are destroyed, they are not being removed from the array, or you wouldn't have had your initial problem :)
Try this ins$$anonymous$$d...
public virtual void Update()
{
bool TurretFound=false;
foreach(GameObject turret in (this.turrets as GameObject[]))
if(turret != null)
{
turret.Send$$anonymous$$essage("Target", this.transform.position);
TurretFound=true;
}
if(!TurretFound)
destroy(gameObject);
}
Finally it worked, I'm still pretty new with C# and Unity. I'm not really that familiar with arrays as this program$$anonymous$$g is on the intermediate to high coding level. Learned something from your help, I really appreciate it Larry, thanks once again.
You are very welcome. Glad I was able to help you!!
Your answer
