Game Development Reference
In-Depth Information
if
(obj
is
GameObjectList)
{
GameObjectList objlist = obj
as
GameObjectList;
GameObject subobj = objlist.Find(id);
if
(subobj !=
null
)
return
subobj;
}
}
return null
;
This may look a bit strange. We are actually calling the method that we are currently
writing. So why does this work? Think about what is happening exactly when the
Find
method is called on an object. If the game object that we are looking for is
inside the list, then this method returns that object. Furthermore, the method calls
the
Find
method on every object that is also of type
GameObjectList
. If none of those
method calls find the object, the method returns
null
. And each of the
Find
method
calls themselves also call the
Find
method on the objects that belong to them that
are of type
GameObjectList
. At some point however, this big 'tree' of
Find
method
calls end, when we reach the bottom of the game object hierarchy. In other words,
at some point there will be no more lists, only game objects. Then, the results of
all the
Find
method calls (either
null
or a game object) are sent back through the
return values. Finally, the first caller of the method gets the object (if it was found
somewhere in the tree), or
null
if no object carrying the requested ID was found.
This kind of search strategy is also called
depth-first
, since we call the
Find
method
on the child object, before examining the rest of the objects in our own list.
When a method calls itself, this is called
recursion
. Recursion is a very powerful
tool, because it allows us to perform these kinds of complicated search algorithms
without having to write a lot of code. However, watch out with recursion, because
you could end up with writing a method that calls itself indefinitely. Suppose that we
want to use recursion to compute the product of two (positive) integers by adding
them up:
public int
Product(unsigned
int
a, unsigned
int
b)
{
−
1, b));
return
(b + Product(a
}
Here, we forgot to check that the product should return 0 if
a==0
. So, the method
calls itself indefinitely, resulting in an endless loop, similar to what can happen if
you forget to increment the counter in the
while
-instruction. The correct version of
this recursive method is, of course:
public int
Product(unsigned
int
a, unsigned
int
b)
{
if
(a == 0)
return
0;