public static void Subscribe(IReceiver receiver, int messageType, ReceiverFunction function) { Debug.Assert(receiver != null, "Receiver can't be null."); Debug.Assert(function != null, "Receiver function can't be null."); Debug.Assert(messageType >= 0, "Message type can't be negative."); addList.Add(new Tuple <IReceiver, int, ReceiverFunction>(receiver, messageType, function)); }
public static void Subscribe(IReceiver receiver, int messageType, ReceiverFunction function) { // Initializing the handle list here simplifies contructors for receiving classes (since they don't all // need to individually create those lists). if (receiver.MessageHandles == null) { receiver.MessageHandles = new List <MessageHandle>(); } if (!functionMap.TryGetValue(messageType, out List <ReceiverFunction> functions)) { functions = new List <ReceiverFunction>(); functionMap.Add(messageType, functions); } int index = -1; // When a class subscribes to a message type, its callback is stored in the first open slot in the function // list (or appended to the end if all slots are filled) for (int i = 0; i < functions.Count; i++) { if (functions[i] == null) { index = i; break; } } // This means that no open slots were found, so the new function must be appended instead. if (index == -1) { functions.Add(function); } else { functions[index] = function; } // It's assumed that the same object won't subscribe to the same message type more than once. If multiple // callbacks are needed, a single lambda can be used to call several functions. receiver.MessageHandles.Add(new MessageHandle(messageType, index)); }