【问题标题】:My unity IEnumerator method not seems to be work我的统一 IEnumerator 方法似乎不起作用
【发布时间】:2019-12-21 04:51:16
【问题描述】:

我有一些代码: 为什么 IEnumerator 方法内的 Debug.Log 不显示任何内容? 为什么我的方法不起作用?

void Update()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            Debug.Log(true);
            MoveInsideTheShape(speedy);
        }
    }

    public IEnumerator MoveInsideTheShape(float speed)
    {
        speed = 1 / speed;
        float totalLenght = cam.orthographicSize * 2;
        float iterationLenght = totalLenght / speed;

        Debug.Log(cam.orthographicSize); // does not work
}

【问题讨论】:

  • 当您只告诉我们“它不起作用”时,您到底希望我们做什么?
  • 你甚至没有从这个函数返回任何东西,所以你希望它如何工作?
  • 您是否收到任何编译器错误?有问题的方法看起来不完整。
  • IEnumerator 永远不会被迭代。我认为您必须在 Unity 中使用某种辅助方法?
  • 为什么你有IEnumerator?而是在这里使用简单的void,因为这里没有循环

标签: c# unity3d yield coroutine yield-return


【解决方案1】:

即使您在 MoveInsideTheShape 方法中缺少返回语句,添加它仍然无法解决您的问题。

IEnumerator 方法必须使用 StartCoroutine 辅助方法进行迭代。

这是一个经过测试的工作代码。

void Update()
{
    if (Input.GetKeyDown(KeyCode.G))
    {
        Debug.Log(true);
        StartCoroutine(MoveInsideTheShape(speedy));
    }
}

public IEnumerator MoveInsideTheShape(float speed)
{
    speed = 1 / speed;
    float totalLenght = cam.orthographicSize * 2;
    float iterationLenght = totalLenght / speed;

    Debug.Log(cam.orthographicSize);

    yield return null;
}

有用的链接:

【讨论】:

  • @SnowyOwl 这是非常值得怀疑的,但如果这应该是一个 IEnumerator/Coroutine 那么因为它可能只是一个普通的 void 方法调用,从上到下运行一次...... .
  • 不知道代码的完整上下文,但是是的,在具体示例中它可能只是一个 void 返回类型的方法。
猜你喜欢
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 2023-02-04
  • 2021-11-27
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
相关资源
最近更新 更多