【问题标题】:Timer function doesnt work (Unity+C#)定时器功能不起作用(Unity+C#)
【发布时间】:2018-03-16 22:47:53
【问题描述】:

我编写了自己的旋转一组对象的函数。我想做一个新的,旋转平稳,所以我需要一个计时器。我曾尝试调用 Timer 几次,但它不起作用。这是我的代码:

public class rotate_around : MonoBehaviour 
{
    public Transform sphere;        

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            sphere.RotateAround(new Vector3(3, 3, 3), new Vector3(0, 1, 0), 45);
            timer();
        }
    }        

    public IEnumerator timer()
    {
        yield return new WaitForSeconds(5);
        // actually I tried to add Debug.Log("blahblahblah") here, but it still didnt output anything
    }
}

【问题讨论】:

  • 至少使用timer().MoveNext();,否则不会调用你的方法和Debug.Log("blahblahblah")

标签: c# unity3d


【解决方案1】:

尝试使用StartCoroutine(timer()); 而不仅仅是timer();

【讨论】:

    【解决方案2】:
    StartCoroutine("timer", true);
    

    这将是最好的方法!

    timer() 只会调用一个普通的方法。 IEnumerator 工作方式不同。

    【讨论】:

    • 缺点是如果你改变了方法的名字,你必须记住在协程中也改变它的名字
    【解决方案3】:

    如前所述,启动协程的正确方法是 StartCoroutine(timer());

    从您的代码中不清楚您要达到的目标,目前您在等待这 5 秒钟后什么都不做

    此外,您可能应该实现某种机制来防止用户向协程发送垃圾邮件。你可以设置一个 bool 标志,或者保持对你启动的协程的引用——我经常这样做

    Coroutine myRoutine; // in global scope
    if (myRoutine==null) myRoutine=StartCoroutine(timer()); // in event handler
    

    myRoutine 完成后会自动归零

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多