Skip to content

Instantly share code, notes, and snippets.

@filipruisl
Forked from bzgeb/Metronome.cs
Created January 24, 2018 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filipruisl/eba3ffff4adde59889c0f836729db458 to your computer and use it in GitHub Desktop.
Save filipruisl/eba3ffff4adde59889c0f836729db458 to your computer and use it in GitHub Desktop.
Pretty solid metronome for Unity
using UnityEngine;
using System.Collections;
public class Metronome : MonoBehaviour
{
public double bpm = 140.0F;
double nextTick = 0.0F; // The next tick in dspTime
double sampleRate = 0.0F;
bool ticked = false;
void Start() {
double startTick = AudioSettings.dspTime;
sampleRate = AudioSettings.outputSampleRate;
nextTick = startTick + (60.0 / bpm);
}
void LateUpdate() {
if ( !ticked && nextTick >= AudioSettings.dspTime ) {
ticked = true;
BroadcastMessage( "OnTick" );
}
}
// Just an example OnTick here
void OnTick() {
Debug.Log( "Tick" );
// GetComponent<AudioSource>().Play();
}
void FixedUpdate() {
double timePerTick = 60.0f / bpm;
double dspTime = AudioSettings.dspTime;
while ( dspTime >= nextTick ) {
ticked = false;
nextTick += timePerTick;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment