Hello!
I have a big coroutine with 2 cycles (one in another). In first cycle its check swayState
, which is enum
. Depends on this enum
, different values sets in variables. After this check, the second cycle begins, that do MoveTowards
stuff depends on previously set variables. In the end swayState
must change, but here is the problem - changing swayState
inside coroutine causes a freeze of unity and I should restart program. I checked through debug, problem is definitely in a changing of swayState
.
I can fix this, making coroutine without one cycle in another, but it won’t be a shot elegant solution, I think. Also I’m just curious the reason of freeze.
private IEnumerator Swaying()
{
Vector2 currentSway = Vector2.zero;
Vector2 targetSway = Vector2.zero;
Ray2D ray;
float randomDirectionX = 0;
float randomDirectionY = 0;
Vector2 randomDirection;
float angleChangeX = 0;
float angleChangeY = 0;
while (true)
{
if (swayingState == SwayingState.RandomMoving)
{
randomDirectionX = UnityEngine.Random.Range(-1f, 1f);
randomDirectionY = UnityEngine.Random.Range(-1f, 1f);
randomDirection = new Vector2(randomDirectionX, randomDirectionY);
ray = new Ray2D(Vector2.zero, randomDirection);
targetSway = ray.GetPoint(swayDistance);
}
else if (swayingState == SwayingState.RandomTurning)
{
angleChangeX = randomDirectionX * swayAngleChange;
angleChangeY = randomDirectionY * swayAngleChange;
randomDirectionX = GetRandomWithinRange(randomDirectionX - angleChangeX, randomDirectionX + angleChangeX);
randomDirectionY = GetRandomWithinRange(randomDirectionY - angleChangeY, randomDirectionY + angleChangeY);
randomDirection = new Vector2(randomDirectionX, randomDirectionY);
ray = new Ray2D(currentSway, randomDirection);
targetSway = ray.GetPoint(swayDistance / 2);
}
else if (swayingState == SwayingState.ReturningToCenter)
{
targetSway = Vector2.zero;
}
while (currentSway != targetSway)
{
Vector2 swayDelta = Vector2.MoveTowards(currentSway, targetSway, swaySpeed) - currentSway;
MoveSight(swayDelta);
currentSway += swayDelta;
yield return new WaitForEndOfFrame();
}
//THE PROBLEM!
if (swayingState == SwayingState.RandomMoving) swayingState = SwayingState.RandomTurning;
else if (swayingState == SwayingState.RandomTurning) swayingState = SwayingState.ReturningToCenter;
else if (swayingState == SwayingState.ReturningToCenter) swayingState = SwayingState.RandomMoving;
yield return new WaitForEndOfFrame();
}
}