Game Development Reference
In-Depth Information
There are several ways such a configuration could be implemented into a C# class. One way would
be to use a two-dimensional array: one dimension for the events and another for the listeners.
Listing 3-6 shows you how this could work in practice by using a two-dimensional array of strings.
Listing 3-6. Using a Two-Dimensional Array to Manage Events and Listeners
using UnityEngine;
using System.Collections;
public class NotificationsManager : MonoBehaviour
{
//Creates an array for 2 Event Types, each allowed a total of 2 listeners (Identified by
GameObject Name)
string[,] Listeners = new string[2,2];
//Function to notify listeners for a matching event (specified by integer ID)
void NotifyListeners (int EventThatHappened)
{
//Loop through listeners
for(int i=0; i<2; i++)
{
//Get listener GameObject in scene based on name
GameObject Listener = GameObject.Find(Listeners[EventThatHappened,i]);
//Notify listener here. Call function.
}
}
}
The chief problem with this approach is its “static” and inflexible nature, which can be found in the
declaration line for the two-dimensional array. There, the maximum array size was specified and fixed
at declaration time to a size of ( 2, 2) , which allows for a total of two events and two listeners. Now,
this wouldn't be troublesome if we knew in advance that we only needed exactly two events and two
listeners for each type; but typically, we don't have such foreknowledge. Typically, we need flexibility.
We need to keep track of any number of events and any number of listeners for each type. If we stick
with fixed-size arrays, we'll usually end up with either more elements than we need, or fewer.
Instead, we'll want an array that sizes itself at runtime to exactly what we need, no more and no less.
Plus, we'll want that array to dynamically change its size, too—to shrink if we remove events and
listeners, and to grow if we add them. This kind of array in which we can add and remove items at
runtime is called a dynamic array , because its size can change to accommodate exactly the number of
items being held at any one time. The disadvantage of dynamic arrays compared to the “conventional”
static arrays pertains to performance. Specifically, dynamic arrays are more computationally expensive
than static ones, as they typically have “more to do” at runtime, such as changing size. For this reason,
it's recommend to always use static arrays when dealing with array-like data whose size and quantity
are known in advance . But often, we'll need to use dynamic arrays just as we do here, because we
can't avoid them effectively.
 
Search WWH ::




Custom Search