好吧,我正在使用我在网上找到的教程进行寻路,并且在协程中添加了航点,我需要访问协程中定义的变量“ 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,这是我猜的默认值。
所以我需要在循环中更新此变量值时访问
预先感谢
答案 0 :(得分:2)
你不能。
在类级别上定义它:
// 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;