爲什麼不循環落後?
// Just change the order from Count - 1 down to 0
for (int i = ObjectManager.Instance.Objects.Count - 1; i >= 0; --i)
{
if (ObjectManager.Instance.Objects[i] is Asteroid)
{
ObjectManager.Instance.Objects.Remove(ObjectManager.Instance.Objects[i]);
}
}
如果你必須循環向前(例如,如果實例應該在創建它們,因爲它們是互相依賴的順序被刪除),你可以以這種方式循環修改:
for (int i = 0; i < ObjectManager.Instance.Objects.Count;) // <- No increment here
if (ObjectManager.Instance.Objects[i] is Asteroid)
ObjectManager.Instance.Objects.Remove(ObjectManager.Instance.Objects[i]);
else
i += 1; // <- Increment should be here!
另一種可能性是的LINQ:
ObjectManager.Instance.Objects.RemoveAll(item => item is Asteroid);
如何以相反的順序進行計數。 –
ObjectManager.Instance.Objects的類型是什麼? –
你可以向後循環 –