Build Queue Logic In Turn-based Strategy

I have a simple build queue in my game - it is currently coded in two lists:

  1. One containing a list of all the units (e.g. footsoldiers, archers
    etc), and
  2. Another list with their respective build time remaining.

It seems to be easy enough to add and remove items from those lists simultaneously, but I am having a bit of a mental block regarding how to go from the point where it is recognized that a unit has been built, to actually instantiating it in game (or taking it from a ready-made stack).

Given that I have quite a long list of potential units, and my game is turn-based (so lightning fast response isn’t necessarily the priority) I decided that I would approach this by making a “unit prefab” that can be programatically customized when the unit is built so that it represents the right thing.

I also made a script called unitStats that contains a class called UnitType, which contains various parameters (attack, defense etc). Within there I have created series of instances of that class (e.g. var footsoldiers = new UnitType) and then defined all the characteristics of each unit separately.

I thought that I could use the following logic:

  1. Update build queue and check if any unit has been completed.
  2. If a unit has been completed then call the BuildUnit function which will,
  3. …create a unit based on the stats held in the appropriate instance of the class in unitStats

The BuildUnit function should take something as a parameter so that the right unit is built (e.g. BuildUnit(unitType: UnitType)) This is where I think I’m stuck - I want to use communicate the UnitType to the BuildUnit function, but I think I’m not quite getting it right.

I’m getting a null reference exception if I try to call BuiltUnit(unitStats.unitType), where I then want the BuildUnit function to use that to set unitType.name, unitType.attack etc…

I imagine I could do this with string and a switch statement, but I feel like I am just getting something simple wrong.

Any ideas?

You should always post code here if you have some and you’re asking a specific code question. But you have the right idea. Your UnitType class should probably have a reference to the Prefab so that you can just instantiate whatever prefab is already set. You can make it serializable so that you can set the value in the inspecter, and then have a list of UnitTypes to choose from. This example is in c#, but you should get the idea:

[System.Serializable]
public class UnitType
{
    public GameObject prefab;
}

public UnitType[] unitTypes;

void BuildUnit(UnitType unitType)
{
    Instantiate(unitType.prefab, position, rotation);
}