Search Unity

BPM Counter / step sequencer

Discussion in 'Scripting' started by Recluse, Apr 23, 2012.

  1. Recluse

    Recluse

    Joined:
    May 16, 2010
    Posts:
    485
    I've just cobbled together a very basic BPM-based sound trigger / sequencer.

    Attach the script to an object with an audiosource (preferably a drum sound - kick, snare, hat) and in the inspector you can set the BPM, the notes on/off pattern, and the step size.

    I've tried a few 4/4 combos around 120 bpm and it seems ok, though I suspect the timing is not as tight as it could be.

    Is there a better method for solid timing than calling InvokeRepeating?

    Code (csharp):
    1. #pragma strict
    2. #pragma implicit
    3. #pragma downcast
    4.  
    5. var BPM : float = 120.0;
    6. private var t : float = 0.0;
    7. var beatgrid : int[]; // in inspector assign 0/1 for beat on/off on individual step
    8. private var beatmarker : int=0;
    9. var steps : int = 4;
    10.  
    11. function Start(){
    12.    
    13.     t = BPM/60.0; // how many beats per second 
    14.     t=(1.0/t)/steps; // divide by steps
    15.     beatmarker=0;
    16.     InvokeRepeating("Trigger",0,t);
    17. }
    18.  
    19.  
    20. function Trigger () {
    21.    
    22.     if (beatgrid[beatmarker]==1)audio.Play();
    23.     beatmarker+=1;
    24.     if (beatmarker>beatgrid.length-1)beatmarker=0;
    25. }
    Feel free to use / modify :)
     
  2. VrTechZx

    VrTechZx

    Joined:
    Mar 11, 2018
    Posts:
    1

    Try Fixed Update :D