keijiro / MidiJack

MIDI input plugin for Unity
697 stars 113 forks source link

MIDI only triggering on second press #24

Closed soniccustard closed 7 years ago

soniccustard commented 7 years ago

Hey, I'm trying to write a script in Unity that allows it to respond to any MIDI note, not just the specified one. In my program it creates an object each time you press a key. It works perfectly with the key numbers assigned, but not when I try it like this. Also the GUI number instantly changes with a key press, but the makeCube bit doesn't do anything until the second press of the same key.

using UnityEngine; using MidiJack;

public class DelegateTester : MonoBehaviour { public GameObject cube; int noteNumber; public Vector3 ObjectSpawnPosition; string noteGUI;

private void Start()
{
    MidiMaster.noteOnDelegate += NoteOn;
}

private void Update()
{

    ObjectSpawnPosition = new Vector3
                (Random.Range(-30f, 30f), Random.Range(-30f, 30f), Random.Range(5f, 120f));

    if (MidiMaster.GetKeyDown(noteNumber))
    {
        makeCube();
    }
}

void NoteOn(MidiChannel channel, int note, float velocity)
{
    noteNumber = note;
    noteGUI = note.ToString();
    Debug.Log("NoteOn: " + channel + "," + note + "," + velocity);
}

void makeCube()
{
    Instantiate(cube, ObjectSpawnPosition, Quaternion.identity);
}

private void OnGUI()
{
    GUI.Label(new Rect(10, 10, Screen.width, Screen.height), noteGUI);
}

}

keijiro commented 7 years ago

This doesn't work because the first invocation of the NoteOn delegate happens inside the first invocation of GetKeyDown.

Workaround: Call GetKeyDown(0) before it. It invokes the NoteOn delegate and you'll get a correct noteNumber. Then, you can do GetKeyDown(noteNumber) correctly.

keijiro commented 7 years ago

I'm closing this issue. Please feel free to reopen if the workaround doesn't work.

soniccustard commented 7 years ago

Thank you so much! You've made my program possible!