Game Development Reference
In-Depth Information
16.2.4 Recursion: A Method Calling Itself
There is one thing that we did not take into account. It is, of course, possible that
one or more of the game objects in the list is itself of the type
GameObjectList
. If that
game object contained a game object with the ID that we seek, then this method
would not find it, since it only checks the game objects that are stored in the list of
the current object (
this
). So how can we solve this? First, we need to check if an
object is of a certain type. For that, we can use the
is
keyword:
if
(obj
is
GameObjectList)
dosomething
Before the
is
keyword, we put the object to be checked, and after the keyword we
place the type. If the object is of the given type, then the expression yields
true
.If
not, the result is
false
. Therefore, we can use it in an
if
-instruction like in the example
above. If we know that the object is of type
GameObjectList
, we can
cast
it and then
try to find the game object that we are looking for in the casted game object list. The
following code does exactly that:
foreach
(GameObject obj
in
gameObjects)
{
if
(obj.ID == id)
return
obj;
if
(obj
is
GameObjectList)
{
GameObjectList objlist = obj
as
GameObjectList;
foreach
(GameObject obj2
in
objlist.gameObjects)
if
(obj2.ID == id)
return
obj2;
}
}
return null
;
So, now we check for each game object to determine if it is of type
GameObjectList
.If
so, we traverse that list's
gameObjects
variable and look for the game object in there.
Are we done now? Well, not really. What if one of the game objects in
objlist
also
is
of type
GameObjectList
? It means that we have to add another layer that checks if one
of the game objects in
that
list perhaps corresponds to the ID that we are looking for.
But one of those game objects could also be of type
GameObjectList
. Obviously, this
approach is not ideal. However, we can do something to avoid this kind of infinite
search problem. Why not use the
Find
method in
objlist
? Look at the following code:
foreach
(GameObject obj
in
gameObjects)
{
if
(obj.ID == id)
return
obj;