让事件每 n 次发生

Make event happen every nth time

我正在尝试创建一个能够响应实时音频输入的摄像头。现在我的代码编写方式是,每次音频输入超过指定的幅度阈值时,相机都会变为随机动画。

振幅阈值是一个介于 0 和 1 之间的值,来自 AudioPeer._audioBand(我的输入)

我想要的是摄像机每 N 次音频超过该阈值时改变位置,而不是每次都改变位置。任何帮助将不胜感激。我是 C# 的新手,谢谢!

void Start()
{
    anim = GetComponent<Animator>();
}


void Update()
{

            if (AudioPeer._audioBand[_band] > .7)
            {
                int randomNumber = Random.Range(1, 4);
                anim.Play("cam" + randomNumber);
            }
        }

    }

只需增加出现次数并使用 remainder operator

The remainder operator % computes the remainder after dividing its left-hand operand by its right-hand operand.

private int _count;
private int _someAmount = 3;

...


if (unchecked(_count++ % _someAmount == 0))
{
      // change camera
}

注意 unchecked 抑制溢出检查并且不会溢出

每个 'nth' 时间很容易用一个简单的计数器模拟,当达到 n 值时重置计数器或使用计数器的模数来确定何时采取行动:

/// <summary>the number of iterations when to act</summary>
private const int n = 7;
/// <summary> member level counter, to track how many times Update() has been called </summary>
private int counter = 0;

void Start()
{
    counter = 7; // reset the counter, but make sure the first time runs.
    anim = GetComponent<Animator>();
}

void Update()
{
    if (AudioPeer._audioBand[_band] > .7)
    {
        counter++;
        if (counter >= n)
        {
            // reset the counter
            counter = 0;
             
            // Execute your logic
            int randomNumber = Random.Range(1, 4);
            anim.Play("cam" + randomNumber);
        }
    }
}

Using if (counter % n == 0) would be simpler, however the value of n might get very large over time and could eventually overflow, so in a long running scenario (which audio processing can easily evolve into) it is better to us a reset pattern.