Understanding Delegates & Callbacks

Using this C# TCP Server example within a Unity project

TcpServer tcpServer1 = new TcpServer(); //in constructor (auto added if added as a component)
  private void openTcpPort(int port)
  {
  tcpServer1.Port = port;
  tcpServer1.Open();
  }

  private void closeTcpPort()
  {
  tcpServer1.Close();
  }

The notes mention There are 3 callback events OnConnect, OnDataAvailable and OnError.
There are 2 callback examples with the following signatures

private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection)

Do I need to do anything special or in addition to enable these callbacks or is tcpServer1_OnDataAvailable considered a reserved handler name that is automatically called?

You need to “subscribe” to an event using “+=” in order to use it.

tcpServer1.OnDataAvailable += tcpServer1_OnDataAvilable;

The actual name doesn’t matter. Usually in C# there are no reserved names… Unity is a special case with some things like Start(), Update(), etc, because those are called by name from Unity’s C++ side.

And you should unsubscribe too, otherwise you’ll create memory leaks. I generally try to subscribe once in Awake and unsubscribe in OnDestroy, and I wrap the unsubscribe in a try-catch.

Also, keep in mind that .NET doesn’t know anything about Unity quirks – scripts on a deactivated GameObject can still be called by other scripts, which means your event delegates can still be called.

1 Like