【问题标题】:How to get access a variable defined in a Coroutine from another class?如何从另一个类访问协程中定义的变量?
【发布时间】:2020-07-28 15:18:41
【问题描述】:

问题是,我正在使用我在网上找到的教程进行寻路,并且航点正在添加到协程中,我需要访问协程中定义的变量“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# unity3d coroutine path-finding game-development


【解决方案1】:

你不能。

改为在类级别定义它:

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

【讨论】:

  • 谢谢,看来我把问题搞砸了:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 2011-10-22
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多