So I’m iterating through a list and adding values to different lists and once I’ve gone through it completely I clear the list and continue. I’m still getting an error however that after googling appears to be about altering lists whilst using them.
private void Awake()
{
generatePlanets();
}
void Start()
{
planetPositions = new List<Vector2>();
lastCirclesPlanets = new List<Vector2>();
}
// Update is called once per frame
void Update()
{
}
private void OnDrawGizmos()
{
generateCircles(amountOfCircles);
drawPlanets();
}
void generateCircles(int amountOfCircles)
{
for (int i = 0; i < amountOfCircles; i++)
{
Gizmos.DrawWireSphere(this.transform.position, firstCircleRadius * i + 1);
}
}
void generatePlanets()
{
//Add starting planet
planetPositions.Add(new Vector2(this.transform.position.x, this.transform.position.y));
lastCirclesPlanets = planetPositions;
for (int i = 0; i < amountOfCircles; i++)
{
currentCircle = i;
List<Vector2> tempList = new List<Vector2>();
tempList = lastCirclesPlanets;
foreach (Vector2 planet in tempList)
{
findNewPlanetPosition(planet, newPlanetsPerCircle);
}
lastCirclesPlanets.Clear();
lastCirclesPlanets = currentCirclesPlanets;
currentCirclesPlanets.Clear();
}
}
void drawPlanets()
{
foreach (Vector2 planet in planetPositions)
{
Gizmos.DrawSphere(planet, planetSize);
}
}
void findNewPlanetPosition(Vector2 planetPosition, int newPlanets)
{
for (int i = 0; i < newPlanets;)
{
for (int j = 0; j < failSafeAttempts; j++)
{
Vector2 angle = Random.insideUnitCircle.normalized;
Vector2 newPosition = planetPosition;
newPosition += (angle * firstCircleRadius) + new Vector2(Random.Range(-1, 2), Random.Range(-1, 2));
//newPosition += (angle * firstCircleRadius);
if (!validateNewPlanet(newPosition)) { }
else
{
currentCirclesPlanets.Add(newPosition);
planetPositions.Add(newPosition);
j = 300;
}
}
i++;
}
}
bool validateNewPlanet(Vector2 newPlanetPosition)
{
//(x-centerpoint.x)^2 + (y-centerpoint.y)^2 < radius^2
if (Mathf.Pow(newPlanetPosition.x, 2) + Mathf.Pow(newPlanetPosition.y, 2) < Mathf.Pow(firstCircleRadius * (currentCircle + 1), 2) && !(Mathf.Pow(newPlanetPosition.x, 2) + Mathf.Pow(newPlanetPosition.y, 2) < Mathf.Pow(firstCircleRadius * (currentCircle), 2)))
{
return true;
}
return false;
}
and the error code it came with:
InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.List1+Enumerator[T].MoveNextRare () (at <9aad1b3a47484d63ba2b3985692d80e9>:0) System.Collections.Generic.List
1+Enumerator[T].MoveNext () (at <9aad1b3a47484d63ba2b3985692d80e9>:0)
GenerateUniverse.generatePlanets () (at Assets/Scripts/Mathijs_Scripts/Generate Universe/Attempt 2/GenerateUniverse.cs:64)
I’ve also attempted making the list into an array (tempList.ToArray()) but when I do this it won’t execute the code completely
If anyone can help me out see what I’m doing wrong that would be great!