c# - 在路点等待统一 C# 中的时间量

标签 c# unity3d coroutine

我在 Unity 2D 项目中有一个路点系统,其中 GameObject 将按顺序跟随每个路点,然后重复该过程,我希望 GameObject 在每个点停止一段固定的时间,我认为我可以实现这使用协程但不完全确定如何实现这一点,到目前为止我所做的是创建一个名为 WaitAtPoint 的协程,然后在每个航路点移动时调用它但无济于事,我不确定我做错了什么。

public class BrainBoss : MonoBehaviour {
[SerializeField]
Transform[] waypoints;

[SerializeField]
float moveSpeed = 2f;

int waypointIndex = 0;


// Start is called before the first frame update
void Start()
{
    transform.position = waypoints[waypointIndex].transform.position;
}

// Update is called once per frame
void Update()
{
    Move();
}

void Move()
{
    transform.position = Vector2.MoveTowards(transform.position, 
        waypoints[waypointIndex].transform.position, moveSpeed * Time.deltaTime);

    if(transform.position == waypoints[waypointIndex].transform.position)
    {
        StartCoroutine(WaitAtPoint());
        waypointIndex += 1;
    }

    if(waypointIndex == waypoints.Length)
    {
        waypointIndex = 1;
    }
}

IEnumerator WaitAtPoint()
{
    yield return new WaitForSeconds(3f);
}

最佳答案

您在每次更新时都调用 Move,您也可以多次调用该 StartCoroutine,所以我建议使用变量来查看您是否应该更新移动

public class BrainBoss : MonoBehaviour
{
[SerializeField]
Transform[] waypoints;

[SerializeField]
float moveSpeed = 2f;

int waypointIndex = 0;
private bool shouldMove = true;


// Start is called before the first frame update
void Start() {
    transform.position = waypoints[waypointIndex].transform.position;
}

// Update is called once per frame
void Update() {
    if (this.shouldMove) {
        Move();
    }
}

void Move() {
    transform.position = Vector2.MoveTowards(transform.position,
        waypoints[waypointIndex].transform.position, moveSpeed * Time.deltaTime);

    if (transform.position == waypoints[waypointIndex].transform.position) {
        StartCoroutine(WaitAtPoint(3));
        waypointIndex += 1;
    }

    if (waypointIndex == waypoints.Length) {
        waypointIndex = 1;
    }
}

IEnumerator WaitAtPoint(int seconds) {
    this.shouldMove = false;
    int counter = seconds;
    while (counter > 0) {
        yield return new WaitForSeconds(1);
        counter--;
    }

    this.shouldMove = true;
}

关于c# - 在路点等待统一 C# 中的时间量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58113719/

相关文章:

c# - 在单声道中学习 C#

c# - 如何在 OpenXML Word 文档中嵌入字体文件

python - 自定义装饰器中的 Tornado 异步操作

c# - 根据类属性引发警告

c# - 无法初始化 AndroidDriver

unity3d - 如何为 Vuforia/Unity 创建 AR 标记?

c# - 在 Unity 5 中从本地服务器创建和下载 Assets 包

ios - 在 iOS 应用程序的一个 View 中使用 Unity3D

android - 将回调 hell 转换为延迟对象

lua协程作为迭代器: cannot resume dead coroutine