- Home /
Unity C# DLL event handling
I've got a C# DLL I created to talk to a serial device since Mono doesn't handle reading the input properly. The DLL targets .NET Framework 3.0 and loads fine. I can reference it and use its functions; however, my event handler doesn't seem to be firing. I'm going to trim it down quite a bit as this part of a much larger project, but the event-handling portion of my DLL looks like this:
public delegate void MessageReceivedHandler(object sender, MessageReceivedEventArgs data);
public event MessageReceivedHandler MessageReceived;
public void OnMessageReceived(MessageReceivedEventArgs data)
{
if (MessageReceived != null)
{
MessageReceived (this, data);
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Get the data with SerialPort.Read(), parse the data, and send it back via MessageReceivedHandler.
}
I reference this DLL in a C# host for testing and it works great. I call a method to send serial data to the device, which triggers a response. Then, when serial data is received on the "port_DataReceived" event, the DLL raises the OnMessageReceived event. The host is subscribed like so:
receiver.MessageReceived += new ReceiverClass.MessageReceivedHandler(ParseReceivedMessage);
My host receives the data perfectly. However, when I set up the DLL in Unity, I can manually call the methods (which perform tasks such as connecting to the serial port and sending data), but the event does not come over. I've confirmed beyond a shadow of a doubt that the methods are working (serial port is connected, messages are being received by the device). I'm just not getting the events like I do in Visual Studio.
Edit: I changed the DLL to simply return a string with the response from a serial request -- no events whatsoever. Again, it works perfectly in a WinForms host, but the same DLL in Unity calls the methods fine, outputs perfectly, but I can't even get a public string to return anything but null.