- Home /
How to remove an object from an array once it has been destroyed
Hi,
I'm working on a script that is attached to the Camera that fades and then shortly after, destroys the object moving towards it. Unfortunately, I'm getting an error just after the object has been destroyed:
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.
FadingTestCam.Update ()
I'm guessing I have to remove the object from the 'Enemies' array ince it has been destroyed, but am not sure how. The script is shown below.
Thanks
private float Dist;
public float FadeDistance;
public GameObject[] Enemies;
void Start()
{
Enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
void Update()
{
foreach (GameObject enemy in Enemies)
{
Dist = Mathf.Abs(transform.position.z - enemy.transform.position.z);
if (enemy.collider.tag == "Enemy" && Dist < FadeDistance)
{
//fade out (level of alpha 0 = transparent, time to take to fade)
iTween.FadeTo(enemy, 0.0f, 0.2f);
StartCoroutine(DestroyObject(enemy));
}
}
}
IEnumerator DestroyObject(GameObject e)
{
yield return new WaitForSeconds(1);
Destroy(e);
}
Answer by aldonaletto · Jul 04, 2012 at 12:28 AM
You could avoid this error by simply checking if the enemy exists - when a game object is destroyed, all of its references become null (don't know how they do this!):
void Update() { foreach (GameObject enemy in Enemies){ if (enemy){ // ignore dead enemies Dist = Mathf.Abs(transform.position.z - enemy.transform.position.z); if (enemy.collider.tag == "Enemy" && Dist < FadeDistance) { //fade out (level of alpha 0 = transparent, time to take to fade) iTween.FadeTo(enemy, 0.0f, 0.2f); Destroy(enemy, 1); // you don't need a coroutine for this! } } } }Removing dead enemies may seem more adequate, but the time spent to recreate the array will be much greater than the time wasted skipping dead enemies - thus I think this is the better solution.
That's great Aldo, agree with you that ignoring the dead enemies is better than re-creating the array - much appreciated! :)
D'oh, completely forgot about the second parameter of Destroy().
Your answer
Follow this Question
Related Questions
Remove an object from an array and destroy it (C#) 2 Answers
Why are Objects not getting destroyed? 0 Answers
Removing objects from an array 2 Answers
Remove object from Array in javascript 1 Answer
Swapping elements of an array 1 Answer