keijiro / OscJack

Lightweight C# implementation of OSC server/client
The Unlicense
465 stars 64 forks source link

Raising an Event with callback #21

Closed sergiobd closed 4 years ago

sergiobd commented 4 years ago

Hi Keijiro,

I tried to raise an UnityEvent inside an OscJack receiving callback. In short:

I'm doing this on start: server.MessageDispatcher.AddCallback(address, GetData);

This is the GetData callback:

    void GetData(string address, OscDataHandle data)
    {

        float time = data.GetElementAsFloat(0);
        float x = data.GetElementAsFloat(1);
        float y = data.GetElementAsFloat(2);
        float z = data.GetElementAsFloat(3);

        linearAccel = new Vector3(x, y, z);

        if (debug)
        {
            Debug.Log("[GetOscDataVector] " + time + " " + linearAccel);
        }

        if (receiveEvent != null)
        {
            receiveEvent.Invoke(time, linearAccel);
        }

    }

where receiveEvent is:

[System.Serializable] public class UnityFloatEvent : UnityEvent<float, Vector3> { }

However, I get this error when the callback is called: UnityEngine.UnityException: get_isPlaying can only be called from the main thread.

Is it is not possible to raise such an event from a data receiving callback?

keijiro commented 4 years ago

Is it is not possible to raise such an event from a data receiving callback?

No, it's not possible. Please check "OSC server class" section in README.

Note that the delegates are to be called in the server thread; You have to queue the events for processing them in the main thread (this will be required in most cases of Unity).