Unit Manager Code Snippet

Just about every strategy game needs a way to manage all the units on the field. Like all the enemy units, all of the player’s units and even neutral entities.

That also means a way for you to easily identify which unit is friendly with each other or enemies.

So here is the pattern I currently use for Riflestorm.

It contains three classes:

  • TeamList - Contains all three teams (or how many you want) with helper methods. Only one is needed.
  • Team - Contains all the team members with helper methods.
  • Entity - This is the individual unit. It’s a dumby file just to illustrate how it’s used.


// create one teamlist for the whole game
TeamList teamList = new TeamList();

// teams are automatically made
teamList.misc; // neutral team
teamList.teamOne; // team one
teamList.teamTwo; // team two

// create an entity and add it to the class
GameObject entityObj = (GameObject)Instantiate(entityPrefab);
Entity entity = entityObj.GetComponent<Entity>();

// add to team one

// entity now has access to it's team
entity.team; // teamList.teamOne
entity.teamId; // can check index in team

// can find entities in the world
teamList.FindEntityAt(new Vector2(0, 0)); // entity

// or find based on team
teamList.teamOne.FindEntityAt(new Vector2(0, 0)); // entity

// entities has it's team instance
entitiy.team.Count; // 1

// can even get the team list instance
entity.team.teamList.FindEntityAt(new Vector2(0, 1)); // null

// can also check if an other entity is friendly
if (entity.IsTeammate(otherEntity)) {
  // true

// can do checks on the team like
teamList.teamOne.IsAllDead(); // false

// or check if at least one is at a location
teamList.teamOne.Some((e) => e.transform.position == Vector2.zero); // true

Handling The Player’s Team

One thing you’ll notice is the teams are not named playerTeam or enemyTeam. That’s because – at least in Riflestorm – the teams are decided at run time, which I feel is best.

I created an other class called level which stores the player team and enemy team – among other things.

if (swapTeams) {
  level.playerTeam = teamList.teamOne;
  level.enemyTeam = teamList.teamTwo;
} else {
  level.playerTeam = teamList.teamTwo;
  level.enemyTeam = teamList.teamOne;

// access like so
if (level.playerTeam.OnTeam(entity)) {
  // on player's team

That’s all, feel free to modify the code to suit your needs.

Download source code:

Related Posts

Test Your Chinese Using This Quiz

Using Sidekiq Iteration and Unique Jobs

Using Radicale with Gnome Calendar

Why I Regret Switching from Jekyll to Middleman for My Blog

Pick Random Item Based on Probability

Quickest Way to Incorporate in Ontario

Creating Chinese Study Decks

Generating Better Random Numbers

Image Magick Tricks

My Game Dev Process