Thursday, 10 February 2011

Searching through a Game component collection

Generally you access the game component collection or the services to find a game component. But what if you want to find a collection within a collection. And what if you only wanted to find the components within a range of the player.

We will look at the Game components collection here. We can use generics and the fact that the Components are a collection using Linq to find the relevant components. Say we have a player class and we want to see all the moving circles around it.

Firstly a generic method in the player class to return a collection of specified components

List<T> FindComponent<T>()
{
return Game.Components.OfType<T>().ToList<T>();
}


NOTE: 


1. This code is called from a game component or you could put it in a static class that can be accessed from anywhere in the game, that has access to the Game object.


Then you can have another method to return the appropriate List of objects.


 


public List<MovingImage> AroundPlayerPos()
{

return FindComponent<MovingImage>();
}


This method can then be further modified to search through the collection using Linq to further qualify what is returned to the calling method.


No comments:

Post a Comment