Reputation: 396
I'm writing a Unity3D game which gets networking events from an external source. The actual network read operations are in their own thread.
When I read some item from the network, I want a Monobehaviour to call some function using that item as an argument in the next Update()
call. Here's how I make that happen right now (just pseudocode for simplicity)
The Network Thread
OtherScript script;
while true {
Thing thing = Network.read()
script.queue.put(thing);
}
The Monobehaviour (OtherScript)
SynchronizedQueue<Thing> queue;
void Update() {
while !queue.isEmpty() {
useThing(queue.pop())
}
}
This definitely works, but my problem is that I'm subscribing to 20+ different types of things, each of which has its own queue and its own "callback" function, resulting in a lot of boilerplate.
Is there some sort of built in mechanism which automates this functionality?
Upvotes: 1
Views: 39
Reputation: 10701
Your solution seems to be in your question. You could use an event instead.
The Network Thread
public static event EventHandler<NetworkArg>RaiseNetwork;
protected void OnNetwork(NetworkArg arg)
{
if(RaiseNetwork != null) { RaiseNetwork(this, arg); }
}
while true {
Thing thing = Network.read()
RaiseNetwork(new NetworkArg(thing));
}
NetworkArg class
public class NetworkArg : System.EventArgs
{
public Thing thing { get; private set;}
public NetworkArg(Thing thing){ this.thing = thing; }
}
The Monobehaviour (OtherScript)
void Start()
{
NetworkThread.RaiseNetwork += UseThing;
}
private void UseThing (object sender, NetworkArg arg){ }
Upvotes: 1