- Home /
How Can I Access a variably from a coroutine?
Well the thing is, Im working on pathfind with a tutorial I found online, and the waypoints are getting added in the coroutine, and I need to access the variable "currentwaypoint" which is defined in the coroutine
public IEnumerator FollowPath()
{
Vector3 currentWayPoint = path[0];
while (true)
{
if (transform.position == currentWayPoint)
{
targetIndex++;
if (targetIndex >= path.Length)
{
targetIndex = 0;
path = new Vector3[0];
reached = true;
yield break;
}
reached = false;
currentWayPoint = path[targetIndex];
lastDir = (currentWayPoint - transform.position).normalized;
}
transform.position = Vector3.MoveTowards(transform.position, currentWayPoint, speed * Time.deltaTime);
transform.rotation = Quaternion.Euler(0, 0, GetAngle(currentWayPoint));
fov.SetAngle(GetAngle(currentWayPoint));
yield return null;
}
but when I do is as adding the "lastDir" variable which is defined outside the Coroutine, it returns only 0,0,0 which is its default value I guess.
So what I need is to access this variables value as it updates in the loop
thanks in advance
Answer by unity_ek98vnTRplGj8Q · Jul 28, 2020 at 03:19 PM
You should be able to access lastDir fine from outside the co-routine. I think the problem is lastDir is never having its value updated because if (transform.position == currentWayPoint)
is never going to return true. There are very few cases where you can get away with checking whether floating point values are equal. In this case, you want to give it a small radius to check within, something like if (Vector3.Distance(transform.position, currentWayPoint) <= 0.2f).
Hopefully this will give you better results. If you are still getting the same results I recommend adding some Debug.Logs to verify that the lastDir variable is actually being updated.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Randomly Spawning 4 cherries in Pacman game (Unity) 1 Answer
Set AI Destination Setter target from Script 2 Answers
Multiple Cars not working 1 Answer