【问题标题】:Trouble with WaitForSeconds() in UnityUnity 中 WaitForSeconds() 的问题
【发布时间】:2014-06-21 00:23:34
【问题描述】:

我正在尝试在更新函数中调用射击动画,然后等待 0.5 秒,然后再生成激光射击。下面的代码对我不起作用。我该怎么做才能达到预期的效果?

void Update()
{
    if (Input.GetMouseButtonDown (0)) 
    {
        animator.SetTrigger("Shoot"); // Start animation

        WaitAndShoot();         
    }
}

IEnumerator WaitAndShoot()
{
    yield return new WaitForSeconds(0.5f);

    Instantiate (shot, shotSpawn.transform.position,shotSpawn.transform.rotation);
}

【问题讨论】:

标签: c# unity3d coroutine


【解决方案1】:

您忘记使用StartCoroutine() 将其作为协程调用。

应该是:

void Update()
{
    if (Input.GetMouseButtonDown (0)) 
    {
        animator.SetTrigger("Shoot"); // Start animation

        StartCoroutine(WaitAndShoot());         
    }
}

IEnumerator WaitAndShoot()
{
    yield return new WaitForSeconds(0.5f);

    Instantiate (shot, shotSpawn.transform.position,shotSpawn.transform.rotation);
}

请记住,这仍然允许您在第一次射击产生之前触发多次射击。如果您想防止这种情况发生,请使用布尔值跟踪射击或未射击,并在 GetMouseButtonDown 之外进行检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多