Game Development Reference
In-Depth Information
public SpriteGameObject( string assetname, int layer = 0, string id = "")
: base (layer, id)
{
sprite = JewelJam.AssetManager.GetSprite(assetname);
}
Similar to this example, most of the GameObject subclasses have been updated in
this way. Take a look at the JewelJam5 project to see how this is done for all the
different game object types.
16.2.3 Finding Game Objects
Although assigning identifiers to game objects might be a good idea, it is only useful
if we also provide a way to find these game objects. To see how this can be done,
let us add a method Find to the GameObjectList class that will look through the list of
game objects to see if any of these game objects have the requested identifier. If the
game object is found, the method returns a reference to this game object, otherwise,
it returns null . The header of our method is then given as follows:
public GameObject Find( string id)
The only thing we have to do now is write the algorithm that examines the game
objects in the list and that returns the game object matching the identifier, if it is con-
tained in the list. We will use the foreach -instruction to do this, although you could
use either the for -instruction or the while -instruction to do the same thing. Inside
the foreach -instruction, we check if the current game object's identifier matches the
requested identifier passed as a parameter to the method. If so, we return that object.
If we did not return from the method in the body of the foreach -instruction, it means
that none of the game objects in the list had the requested ID, so the method returns
null . The body of the Find method then becomes
foreach (GameObject obj in gameObjects)
if (obj.ID == id)
return obj;
return null ;
Note that once the return instruction is executed, we return immediately from the
method. This means that the remaining game objects are not checked anymore. Fur-
thermore, we do not check if game objects have duplicate IDs. If there are multiple
game objects that carry the same ID, this method returns the first one that it finds.
Search WWH ::




Custom Search