【问题标题】:Unable to get coroutine to start and stop when button is down按钮按下时无法启动和停止协程
【发布时间】:2019-06-19 19:46:51
【问题描述】:

我正在为我的游戏制作行走声音,我希望它播放一个声音,然后等待播放下一个声音。当它在行走时,我只希望它在按下 w 时这样做。我一直在尝试使用 Enumerator 来执行此操作,但我遇到了无法启动该功能的问题。

  private IEnumerator audioPlayCoroutine;

public AudioSource[] steps;
public AudioSource[] cabinSteps;

private bool running;

void Start()
{
    running = false;

    audioPlayCoroutine = AudioPlay();
}
void Update()
{
    if (Input.GetKey("w"))
    {
        if (running == false)
        {
            running = true;
        }
    }

    if (running == true)
    {
        StartCoroutine(audioPlayCoroutine);
    }

    else if (running == false)
    {
        StopCoroutine(audioPlayCoroutine);
    }

}
IEnumerator AudioPlay()
{
    int ran = Random.Range(0, 4);        

    steps[ran].Play();

    yield return new WaitForSeconds(2);
}

【问题讨论】:

    标签: c# unity3d coroutine


    【解决方案1】:

    好的,它不起作用的原因有多种:

    对于一个running 永远不会设置为false。一旦您的播放器按下w 一次,它将保持true。 而是写

    if (Input.GetKey("w"))
      running = true;
    else
      running = false;
    

    此外,您还可以多次启动和停止 Coroutine。 相反,您应该检查运行状态是否已更改,或者您应该只检查协程中的running。 它可能看起来像这样:

    void Start() {
      running = false;
      audioPlayCoroutine = AudioPlay();
      StartCoroutine(audioPlayCoroutine);
    }
    
    void Update() {
      if (Input.GetKey("w"))
        running = true;
      else
        running = false;
    }
    
    IEnumerator AudioPlay()
    {
      while (true) {
        if(!running)
          yield return new WaitForSeconds(0);
    
        int ran = Random.Range(0, 4);  
    
        steps[ran].Play();
    
        // if you want it to play continuously, you can use the clip length for
        //   the sleep. This way it will start playing the next clip right after 
        //   this one is done. If you don't want that, go with your code
        yield return new WaitForSeconds(steps[ran].clip.length);
      }
    }
    

    如果您的剪辑实际上有 2 秒长,您可能还想在用户停止按下按钮后中断它的播放。

    【讨论】:

    • 您可以通过保持协程本身不变并在 GetKeyDown() 上调用 StartCoroutine 并在 GetKeyUp() 上调用 StopCoroutine 来获得一些效率
    • @MarekLegris 也许,但您所做的只是更改另外两个布尔检查(GetKey!running)(KeyUp 和 KeyDown),因此性能基本上只是一种方法调用与启动和停止协程。所以,虽然它可能更快,但也可能不是(我需要一些基准测试;除非我真的错过了一些东西)而且我认为这样的代码可读性更好,我会接受它性能小幅提升。
    • 可读性评级是个人喜好,我尊重这一点,只是想给出我的看法。
    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多