jorgegarcia / UnityOSC

Open Sound Control (OSC) C# classes interface for the Unity3d game engine
497 stars 124 forks source link

Timing Problem/Question (Packet loss?) #14

Open michaelbaisch opened 8 years ago

michaelbaisch commented 8 years ago

Hi,

I send a lot of OSC packets to UnityOSC. And the current packet was more and more in the past. So I looked a bit in the code and I found that every 10ms a new packet is received. So I guess that's the limit for receiving packets. Next thing I noticed is that _lastReceivedPacket is just overridden in the Receive() function. So when the logs are updated in the UpdateLogs() function, it takes the last one but this happens maybe every 16ms (60fps) if you call I call it in my Update() function, so there could be packet loss right?

So I thought it would be maybe be a good idea to give the developers also an option to have access to the PacketReceivedEvent. Just to try that out I replaced the void OnPacketReceived(OSCServer server, OSCPacket packet) with

public delegate void OSCPacketReceived(OSCServer server, OSCPacket packet);
public static event OSCPacketReceived OnOSCPacketReceived;

void OnPacketReceived(OSCServer server, OSCPacket packet)
{
    if(OnOSCPacketReceived != null){
        OnOSCPacketReceived(server, packet);
    }
}

Then I could do something like this in my script: OSCHandler.OnOSCPacketReceived += OnPacketReceived; I then figured out that this runs in another thread which makes sense, so I can't directly change gameobjects. So there needs some kind of copying step before, so I looked how this is solved in UnityOSC and the _lastReceivedPacket is just written and read without any locking. Couldn't there be any problems with writing and reading at the same here?

jorgegarcia commented 8 years ago

Hi @michaelbaisch,

Thanks for opening this issue. You have some valid points.

The limit for receiving packets is indeed limited in part by the Update() calls on the Unity application. A better way would be (as you mention) using the delegate asynchronously. If the _lastReceivedPacket is going to be read/written from different threads, I agree that it would need some kind of locking mechanism.

If you manage to have it all working and you can test it, please feel free to do a pull request with the changes.

Cheers, Jorge