Hello!
This is my first time posting on Unity’s forums, so feel free to tell me if I’m doing something wrong or posting in the wrong location.
Within my program, there are small circles which will move around within a larger bounded area, by choosing a random point within a circle. There are multiple of these bounded areas within the scene, each with some amount of circles moving around within. Every once in a while (with chance travelChance), I want a circle to move to another bounded area and travel between them.
All the local movement works fine, but when I try and run the program with the movement between areas, Unity freezes up and I need to relaunch. I suspect there is some sort of infinite loop which is going on, but I couldn’t find out where.
Below is the code for the update function and coroutine within the circle prefab.
void Update()
{
if (Time.time >= nextMoveTime)
{
nextMoveTime += timeBetweenMoves;
if (Random.Range(0f, 1) < travelChance && isTravelling != true) //travelChance is a decimal between 0 and 1
{
while (boxIndices[0] == currentBoxIndex) //boxindices is a list containing the indices of all possible boxes you can travel to
{
boxIndices = boxIndices.OrderBy(x => Random.value).ToList(); //randomizes the list
}
destinationIndex = boxIndices[0]; //we want to travel to a random box
float randX = Random.Range(boxTransforms[destinationIndex].leftWall.position.x, boxTransforms[destinationIndex].rightWall.position.x); //boxtransforms is a list of struct Box, which contains the transforms of the four walls
float randY = Random.Range(boxTransforms[destinationIndex].botWall.position.y, boxTransforms[destinationIndex].topWall.position.y);
travelDestination = new Vector2(randX, randY); //a random location within the random box
isTravelling = true;
StartCoroutine(travelBetweenBox());
}
movedestination = Random.insideUnitCircle * moveRadius + (Vector2)transform.position; //destination of a regular move is a random point within a circle of radius moveRadius
while (movedestination is within the boundaries of boxTransforms[currentBoxIndex])
{
movedestination = Random.insideUnitCircle * moveRadius + (Vector2)transform.position;
}
}
if (isTravelling == false)
{
transform.position = Vector2.MoveTowards(transform.position, movedestination, movespeed * Time.deltaTime);
}
}
IEnumerator travelBetweenBox()
{
while (Vector2.Distance((Vector2)transform.position, travelDestination) > 0.2f)
{
transform.position = Vector2.MoveTowards(transform.position, travelDestination, travelSpeed * Time.deltaTime);
yield return null;
}
isTravelling = false;
currentBoxIndex = destinationIndex;
}