In Unity 2022.3.12f1, I made a metronome. Here is a minimal working example:
using System;
using UnityEngine;
public class Metronome : MonoBehaviour
{
public int tempo = 150;
public int tempoReference = 4; //e.g., 4 means reference is a quarter note, 2 means reference is a double note,...
public int timeSignatureTop = 4;
public int timeSignatureBottom = 4;
public AudioSource source; //You have to fill this with any short sound
private float delayBeforeNextBeat;
private float beatDuration = 0;
private bool play = false;
private int beatIndex = 0;
public void Start()
{
source.Play();
beatDuration = 60f / (timeSignatureBottom / tempoReference * tempo);
delayBeforeNextBeat = beatDuration;
beatIndex = 0;
play = true;
}
private void Update()
{
if (play)
{
delayBeforeNextBeat -= Time.deltaTime;
if (delayBeforeNextBeat <= 0)
{
beatIndex = (beatIndex + 1) % timeSignatureTop;
delayBeforeNextBeat = beatDuration + delayBeforeNextBeat;
source.Play();
}
}
}
}
My problem is that the interval between the first two beats (as heard through the AudioSource) is much longer that the next ones. Additional prints indicate that Time.deltaTimes are not particularly longer nor more numerous in this interval than they are in others, though.
I tried to move everything in FixedUpdate, with the same result.
I also tried to move the first source.Play() inside the Update function (with some minor adjustments, like adding a bool firstPlay and initializing beatIndex to -1), with the same result.
Does somebody have an idea?