c# - 如何从另一个类访问协程中定义的变量?
问题描述
好吧,我正在使用我在网上找到的教程进行寻路,并且航点正在添加到协程中,我需要访问在协程中定义的变量“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,这是我猜的默认值。
所以我需要的是访问这个变量值,因为它在循环中更新
提前致谢
解决方案
你不能。
改为在类级别定义它:
// 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;
推荐阅读
- nativescript - sidedrawer.d.ts 中的 nativescript-ui-sidedrawer,找不到 TKView、TKTheme 等
- angular - 角度 - 检测通过单向绑定改变值
- c++ - 您将如何读取 GPU 的前端缓冲区以获取屏幕?
- c# - Null Coalescing Operator 比自己执行逻辑更快?
- python - 我不能将 if 语句与数学运算一起使用吗?
- python - pyinstall 不能使用选项 --noconsole
- drake - 可视化多个机器人的运动
- laravel - 如何在 MacOs 10.14 上设置工作虚拟主机?
- apache-flink - 事件时间窗口的结束时间戳不能通过合并变得早于当前水印
- android - 如何将 GoogleSignInClient 实例从一项活动传递到另一项活动