- Home /
Array.Count returning 0 out of the foreach and 4 inside
List<GameObject> bestWay() {
List<GameObject> bestWay = new List<GameObject>();
GameObject[] wayPoints = GameObject.FindGameObjectsWithTag("wayPoint");
foreach(GameObject wp in wayPoints) {
bool colEnemyWp = Physics.Linecast(myTrans.position, wp.transform.position);
bool colWpTarget = Physics.Linecast(wp.transform.position, myTrans.position);
if((!colEnemyWp) && (!colWpTarget))
{
possibleWays.Add(wp);
}
}
if(possibleWays.Count > 1)
{
float minorTotalMovement = Mathf.Infinity;
foreach(GameObject wp in bestWay)
{
float curTotalMovement = Vector3.Distance(myTrans.position, wp.transform.position) +
Vector3.Distance(wp.transform.position, Player.transform.position);
if(curTotalMovement < minorTotalMovement)
{
minorTotalMovement = curTotalMovement;
} else
{
bestWay.Remove(wp);
}
}
}
bestWay = possibleWays;
return new List<GameObject>(bestWay);
}
I want to know why 'possibleWays.Count' returns me 0 out of the foreach and inside it returns me 4?
Thanks from now!
*Is it something wrong about asking a lot in here? Because I'm doing this :(
But, as always, some help would be appreciated! Thanks from now!
Answer by Bunny83 · Mar 02, 2012 at 02:21 AM
You can't remove elements inside a foreach loop. That will break the enumerator. You have to loop manually. Just loop backwards and you're safe.
for(int i = bestWay.count-1; i>=0 ;i--)
{
GameObject wp = bestWay[i];
//[...]
{
bestWay.RemoveAt(i);
}
}
This way the indices doesn't get screwed up.
I've just found another thing... Your bestWay array never got filled with items and just get overwritten at the end.
You should make yourself clear about the usage of bestWay
and possibleWays
. It seems you mixed them up...
Your answer
Follow this Question
Related Questions
Change part of a string [Solved] 3 Answers
Array simple problem 1 Answer
how to get game object by string? 0 Answers