Reputation: 36311
So, I am trying to loop through a list and remove the items from the list and and Destroy the GameObject, so at first I did this:
Pooler.Remove()
protected static void Remove(GameObject obj){
PoolerItem p = (
from item in pool
where obj == item.gameObject
select item
).FirstOrDefault();
pool.Remove(p);
GameObject.Destroy(p.gameObject);
}
Loop Through a list
foreach(PoolerItem p in pool.Where(x => x.poolName == "cube")){
if(totalItems > minPoolSize && p.inactiveLifeSpan > 0 && !p.gameObject.activeSelf && Time.time - p.disableTime >= p.inactiveLifeSpan){
Pooler.Remove(p);
}
}
I get an error that basically says You can delete items from the list you are looping over
Okay, makes sense. So I looked around and saw that I should use RemoveAll
so I created the code for that and replaced it with my foreach like this:
pool.RemoveAll(
p => p.poolName == entry.poolGroupName
&& p.inactiveLifeSpan > 0
&& !p.gameObject.activeSelf
&& Time.time - p.disableTime >= p.inactiveLifeSpan
);
The only thing that is missing is this line GameObject.Destroy(p.gameObject);
from Pooler.Remove
. How can I implement that with pool.RemoveAll()
?
Upvotes: 0
Views: 359
Reputation: 101681
You can use a statement lambda instead of expression, and you can do whatever you want inside it:
pool.RemoveAll(
p => {
if(p.poolName == entry.poolGroupName &&
p.inactiveLifeSpan > 0 &&
!p.gameObject.activeSelf &&
Time.time - p.disableTime >= p.inactiveLifeSpan)
{
GameObject.Destroy(p.gameObject);
return true;
}
return false;
});
Upvotes: 3