为什么不将null GameObjects从List中删除?

时间:2016-03-07 00:16:05

标签: c# unity3d unityscript

由于某种原因,我在函数TargetEnemy()底部的代码不起作用。我尝试从List中删除null GameObjects,但它们仍然在列表中。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TurretController : MonoBehaviour {

    public Transform turretBulletSpawn;
    public GameObject turretBullet;

    public List <GameObject> storedEnemies = new List <GameObject>();

    void Start () 
    {

    }

    void Update ()
    {
        TargetEnemy();
    }

    public void OnTriggerEnter (Collider enemyTriggered)
    {
        if (enemyTriggered.tag == "Enemy")
        {
            storedEnemies.Add(enemyTriggered.gameObject);
        }
    }

    public void OnTriggerExit (Collider enemyTriggered)
    {
        storedEnemies.Remove(enemyTriggered.gameObject);
    }

    void TargetEnemy()
    {
        for (int i = 0; i < storedEnemies.Count; i++)
        {
            Quaternion rotate = Quaternion.LookRotation(storedEnemies[i].transform.position - transform.position);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * 2);
            Instantiate (turretBullet, turretBulletSpawn.position, turretBulletSpawn.rotation);

            if (storedEnemies[i].gameObject == null)
            {
                storedEnemies.RemoveAt(i);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

有一个巨大的错误,你应该试着记住这个偶然! 让我们假设targetEnemy有3条记录,第二条记录为null。 我们还假设您的代码将正确删除空记录。

前两个记录将被正确处理。 但在第三次迭代之前,您的列表只包含2条记录,而您正尝试访问第三条记录。这将抛出IndexOutOfrange或IndexOutOfBounds异常。

这是正确的:

List<int> toRemove = new List<int>();

for(int i = 0; i < storedEnemies.Count; i++) {
   /*some code*/

   if(storedEnemies[i].gameObject == null) {
      toRemove.Add(i); //Note: I do not change your targetEnemy List
   }
}

//Iterate again and remove all stored indexes
int counter = 0;
for(int i = 0; i < toRemove.Count; i++) {
   storedEnemies.Remove(i - counter);
   counter++;
}