i have a trouble with code below. What it does it builds a single line of road, one element after another.
currentLength = Random.Range(maxFloorLength - 2, maxFloorLength);
List<GameObject> tempList = new List<GameObject>();
for (int i = 0; i < currentLength; ++i)
{
foreach (GameObject g in pooledFloor)
{
if (!g.activeInHierarchy)
{
g.SetActive(true);
g.transform.position = startPoint + buildDirection * i;
g.transform.DOScaleY(5, 0.25f).Play();
lastFloorPositions.Add(g.transform.position);
tempList.Add(g);
break;
}
}
yield return new WaitForSeconds(0.05f);
}
While this works as expected, when i change this to:
currentLength = Random.Range(maxFloorLength - 2, maxFloorLength);
List<GameObject> tempList = new List<GameObject>();
for (int i = 0; i < currentLength; ++i)
{
foreach (GameObject g in pooledFloor)
{
if (!g.activeInHierarchy)
{
g.transform.position = startPoint + buildDirection * i;
lastFloorPositions.Add(g.transform.position);
tempList.Add(g);
break;
}
}
}
foreach (GameObject g in tempList)
{
g.SetActive(true);
g.transform.DOScaleY(5, 0.25f).Play();
yield return new WaitForSeconds(0.05f);
}
all it does is create ONE part of road (the one that should be at the end of tempList list). What i want is that script adds all the prefabs to list BEFORE doing something else with them, so i can add few thing in between. I tried to change it to void function, and calling some of this code as ienumerator, changing loop types etc. but nothing seems to work and i have no clue why is it not working. I checked with Debug.Log whether it still finds more than 1 prefab, and it does, but it only activates and scales ONE of them. I bet it's something obvious, but i just can't see it :/
How it looks:
How it should be looking:
Forgot to mention - its all inside of IEnumerator
In first code when you call g.SetActive(true);
, in next iteration of for
loop the if
condition for the same object wont be true so it will evaluate for next inactive object and add it to tempList
.
In second case for all iteration of for loop
it keeps evaluating for same object g (the first inactive object on pooledFloor
) because it is not being activated.
To achieve your expected behaviour, I would suggest you to use for-loop
instead of for-each
on pooledFloor
and remove the object from the list if its inactive.
something like this:
for (int i = 0; i < currentLength; ++i)
{
for (int j = 0; j < pooledFloor.Count; j++)
{
GameObject g = pooledFloor[j];
if (!g.activeInHierarchy)
{
g.transform.position = startPoint + buildDirection * i;
lastFloorPositions.Add(g.transform.position);
tempList.Add(g);
pooledFloor.Remove(g); // Removing it from list would solve the problem.
break;
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments