- Home /
C# Coroutine help
I am currently working on a waypoint script. The waypoint counter should advance when the object is in range of the waypoint. That works fine, but I also want to add a time delay. The following except seems to add a wait time to the first waypoint, however subsequent waypoints do no wait. Does anyone have any idea why its not working? I feel like there is a much simpler way to do this.
void Update ()
{
//bunch of stuff to make the guy move to waypoints
if ((alternativeWaypoint[currentWaypoint].position - transform.position).sqrMagnitude < 1)
{
print("close");
StartCoroutine(WaypointCounter());
if ( addWaypoint == true)
{
currentWaypoint++;
addWaypoint = false;
}
}
}
IEnumerator WaypointCounter()
{
yield return new WaitForSeconds(10);
print("someting");
CurrentWaypointAdd();
}
void CurrentWaypointAdd ()
{
addWaypoint = true;
}
Thanks
Answer by Bunny83 · Jul 21, 2011 at 11:24 PM
When you come in range of the waypoint you start a new coroutine EVERY frame. So after 1 sec at 60fps there are 60 coroutines running...
You should use your boolean to "block" the execution of the coroutine when you reached the waypoint.
Something like that:
bool reachedWaypoint = false;
void Update ()
{
if (!reachedWaypoint && ((alternativeWaypoint[currentWaypoint].position - transform.position).sqrMagnitude < 1))
{
reachedWaypoint = true;
StartCoroutine(SetNextWaypointDelayed());
}
}
IEnumerator SetNextWaypointDelayed()
{
yield return new WaitForSeconds(10);
SetNextWaypoint();
}
void SetNextWaypoint()
{
currentWaypoint++;
reachedWaypoint = false;
}
Your answer
Follow this Question
Related Questions
Trouble Resuming after Yielding while Inside Coroutine 1 Answer
WaitForSeconds Question 2 Answers
Waypoint / Yield help 1 Answer
C# yield not working. 2 Answers
Waiting twice inside coroutine (C#) 2 Answers