-
-
Save filipruisl/eba3ffff4adde59889c0f836729db458 to your computer and use it in GitHub Desktop.
Pretty solid metronome for Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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