首页 > 解决方案 > 如何从另一个类访问协程中定义的变量?

问题描述

好吧,我正在使用我在网上找到的教程进行寻路,并且航点正在添加到协程中,我需要访问在协程中定义的变量“currentwaypoint”

 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;
        }

但是当我添加在协程外部定义的“lastDir”变量时,它只返回 0,0,0,这是我猜的默认值。

所以我需要的是访问这个变量值,因为它在循环中更新

提前致谢

标签: c#unity3dcoroutinepath-findinggame-development

解决方案


你不能。

改为在类级别定义它:

// The value you actually store and update
private Vector3 currentWayPoint;

// A public Read-Only property for everyone else
public Vector3 CurrentWayPoint => currentWayPoint;

public IEnumerator FollowPath()
{
    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;
    }
}

所以另一个脚本会去

var waypoint = someObject.GetComponent<YourClass>().CurrentWayPoint;

推荐阅读