c# - 充电能量并在按住鼠标按钮时释放它

标签 c# unity3d

我需要积累一定的能量并在松开鼠标按钮时释放它。现在,当能量水平达到最大值时,能量水平被设置为 0,并且该函数刚刚重新开始从头开始累加,从而创建一个循环。

IEnumerator AttackCharge()
{
    while (true)
    {
        if (Input.GetMouseButton(1) && energyLevel < energyMax)
        {
            energyLevel += 1;

            yield return new WaitForSeconds(playRate);
        }

        if (Input.GetMouseButtonUp(1))
        {
            if (energyLevel == energyMax)
            {
                FxPlayerAttack.Stop();
                FxPlayerAttack.Play();
                shootSound.PlayOneShot(attackSound);

                GetComponentInChildren<ParticleCollision>().attackValue = energyLevel;
                yield return new WaitForSeconds(2);

                energyLevel = 0;
                GetComponentInChildren<ParticleCollision>().attackValue = energyLevel;
            }

            if (energyLevel < energyMax)
            {
                yield return new WaitForSeconds(2);
                energyLevel = 0;
            }
        }
        yield return null;
    }
}

我需要在按住按钮时积累能量。当按钮为 Up 时,能量应在充电阶段达到最大值时释放,能量水平应返回 0 并停止累积,直到再次按下按钮。

最佳答案

GetMouseButtonUp 仅在释放按钮的单帧 上返回 true。然后您的代码yield

让我们走一遍:

if (Input.GetMouseButton(1) ...

用户为了攻击而松开了鼠标,所以这是错误的。

else {
    yield return null;
}

所以你屈服并等待下一帧。然后当执行恢复时:

if (Input.GetMouseButtonUp(1))

这是错误的,因为用户在最后 帧释放了鼠标按钮。您应该将整个 block 嵌套在 yield return null 行的 else 语句中。

关于c# - 充电能量并在按住鼠标按钮时释放它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311967/

相关文章:

c# - 单元格中的 Excel XML 换行符

unity3d - Unity iPhone 应用程序大小太大

c# - 未调用 ReadJson

database - 如何在没有在线数据库的情况下存储游戏数据

c# - 如何将对 System.Data.DataSetExtensions 的引用添加到网站 ascx.cs 文件?

c# 将 Json 加载到继承类中

c# - IEnumerable.Select() 可以跳过一个项目吗?

c# - C#中的字符串常量内存池

c# - 继承逻辑 : PlayerBase and Player scripts childs

c# - 当 PlaneFinderBehaviour 使用 Vuforia 7 接收输入时触发自定义方法