繁体   English   中英

我怎样才能概括这两个协程,所以我只使用一个? (在参数中输入一个布尔值并从内部设置)

[英]How can I generalize these two coroutines so I only use one? (Input a boolean into the parameters and set from within)

我正在编写一些脚本,我有以下两个协程:

private IEnumerator blockTimer(float duration)
{
    blocking = true;
    yield return new WaitForSeconds(duration);
    blocking = false;

    movementCooldown = true;
    sprite.color = Color.green;
    yield return new WaitForSeconds(duration);
    movementCooldown = false;

    sprite.color = Color.white;

    yield return null;
}
private IEnumerator dashTimer(float duration)
{
    dashing = true;
    yield return new WaitForSeconds(duration);
    dashing = false;

    movementCooldown = true;
    sprite.color = Color.green;
    yield return new WaitForSeconds(duration);
    movementCooldown = false;

    sprite.color = Color.white;

    yield return null;
}

在我的更新函数中根据不同的输入调用它们:

private void Update()
{
    if (dashing || blocking || movementCooldown) return;
    if (Input.GetButtonDown("Dash") & (movementX!=0||movementY!=0))
    {
        sprite.color = Color.red;
        StartCoroutine(dashTimer(dashTime));
    }
    if (Input.GetButtonDown("Block"))
    {
        sprite.color = Color.blue;
        StartCoroutine(blockTimer(blockTime));
        
    }
}

显然,这两个协程非常相似。 我一直在尝试一些不同的方法来概括它们。 我只是无法弄清楚我是如何将 bool 作为参数传递给一个通用协程并从内部设置它的。 我可以通过直接指向布尔值来设置布尔值,但是我如何制作它以便可以调用参数 bool 并在协程期间对其进行更新? 任何帮助深表感谢!

您可以使用回调函数作为参数,如下所示:

private IEnumerator GenericTimer(float duration, Func<bool, bool> callback)
    {
        callback(true);
        yield return new WaitForSeconds(duration);
        callback(false);

        movementCooldown = true;
        sprite.color = Color.green;
        yield return new WaitForSeconds(duration);
        movementCooldown = false;

        sprite.color = Color.white;
    }

然后你只需创建一个 lambda,将此值分配给阻塞或破折号变量:

private void Update()
    {
        if (dashing || blocking || movementCooldown) return;
        if (Input.GetButtonDown("Dash") & (movementX!=0||movementY!=0))
        {
            sprite.color = Color.red;
            StartCoroutine(GenericTimer(dashTime, (bool value) => dashing = value));
        }
        if (Input.GetButtonDown("Block"))
        {
            sprite.color = Color.blue;
            StartCoroutine(GenericTimer(blockTime, (bool value) => blocking = value));
            
        }
    }
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM