Army Troops

👍

Reminder - Keep Daily Backups

When working on a strategy game with a kit as big as the Complete Kit - always keep a working daily backup! Save yourself the trouble of rolling-back changes and losing work.

What is the army?

When playing battle strategy games you'll always be able to build an army, or heros for battle to attack other player bases and gain in-game resources that you steal from other player bases.

589

Viking demo character attacking another player's base.

The demo includes a few characters for you to play with, most notably the viking, archer, and mage. Plus we have extra bonus characters premade for developers included in the download center for the highest package kit owners.

About the Shop Menu

Here's a screenshot of the shop menu for your army troops.

636

Click to view larger.

Inside the Troops shop menu you can drag and scroll right to see all the units you can built in your game. Click any of the buttons under each unit to begin training.

765

Click to view larger.

About the unit training queue

600

Training queue. Click to view larger.

Item From Image AboveDescription
Unit production queueThis list fills up from right to left with the units the player is currently training. Each type of unit gets one slot on this bar.
Prefab imageThe image for the unit in the queue shows here
Remove one unit from queueClick the (X) to remove one unit from that queue item. If there is only one unit remaining, the queue item is removed and units further up in the queue are moved forward.
Units remainingThe units remaining to be trained
Gem cost to finish nowThe rare currency cost to finish now. This increases based on the training time remaining. As of now, this is hardcoded into MenuUnit.cs (see below for documentation about gem cost for training times)
Training progress bar (one unit)The progress bar under each unit represents the time remaining until one unit is trained. When it completes, the units remaining is decreased by one meanwhile the player's units are increased by one.

Store Item

All of the store details seen in the below screenshot are taken from the XML/Units.xml file and loaded by Scripts/Units/MenuUnit.cs (details below on what part of the script does this)

463

Breakdown of the information shown to players in the store.

From Image AboveDescription
Item NameThis is the Name variable from XML/Units.xml
Time to BuildThe TimeToBuild variable (in minutes) from Units.xml. How long the structure will take to to be created.
Currency CostThe Price variable from XML/Units.xml
Currency TypeThe Currency variable from XML/Units.xml (Either Gold, Mana, or Gems) You could change this to whatever currency you will have in your game and also add additional currencies.
View DescriptionShows the Description text variable from XML/Units.xml
Prefab ImageThe prefab image which you can edit from the UIAnchor: Center shop main menu.

What happens when a unit finishes production?

When a unit finishes production, they move from the production queue (MenuUnit.cs) to the player's population array. (Stats.cs)

435

When a unit finishes production, they move to the player's unit.

private void FinishObject()
	{		
		int objIndex = ((QIndex)activeQueList[0].GetComponent("QIndex")).objindex;
		UnBuild(objIndex,1);	
		((Stats)stats).existingUnits[objIndex]++;
		((Stats)stats).UpdateUnitsNo();
	}

How much does it cost to finish production now for units?

The following excerpt from Scripts/Units/MenuUnit.cs shows the game settings for how the total price is computed in crystals based on the total minutes remaining in the production queue.

For example, if time remaining is less than 30 minutes then it only costs one crystal gem to finish production of all units. Once the total time remaining exceeds 30 minutes but is less than 60 minutes the price increases to 3 crystal gems, and so on.

You can adjust these settings in MenuUnit.cs. Look for the following source code:

if (timeRemaining >= 4320)	priceInCrystals = 150;
		else if (timeRemaining >= 2880)	priceInCrystals = 70;
		else if (timeRemaining >= 1440)	priceInCrystals = 45;
		else if (timeRemaining >= 600)	priceInCrystals = 30;
		else if (timeRemaining >= 180)	priceInCrystals = 15;
		else if (timeRemaining >= 60)	priceInCrystals = 7;
		else if (timeRemaining >= 30)	priceInCrystals = 3;
		else if (timeRemaining >= 0)	priceInCrystals = 1;

What happens when the player accelerates production with a gem?

Once the player clicks the gem acceleration button, a few things happen all at once. First we check if the Player crystal stats is greater than the total crystal price. If not, we show an error. Otherwise we increase the population and erase all the unit data in the training queue array.

public void FinishNow()
	{
		if (priceInCrystals <= ((Stats)stats).crystals) 
		{
      // Deduct the crystals and then trigger a UI update
			((Stats)stats).crystals -= priceInCrystals;	
			((Stats)stats).UpdateUI();
			((UILabel)HintLabel).text ="Training complete.";
      
      // Update the population with the units from the queue
			IncreasePopulation();
      
      // Run this function to update the stats UI 
      // (otherwise the new numbers won't show until this runs at a later point in time)
			((Stats)stats).UpdateUnitsNo();
      
      // Remove all the unit data from the queue
			EraseValues();
		} 

		else if(timeRemaining > 0)			
		{
			((Messenger)statusMsg).DisplayMessage("Not enough crystals");
		}
	}


// Increases population by cyling through all the units in training
// and adding them to the player array
	private void IncreasePopulation()
	{
		for (int i = 0; i < trainingIndexes.Length; i++) 
		{			
			if(trainingIndexes[i]>0)
			{
				int a = trainingIndexes[i];		
        //trainingIndexes[i] is modified in loop - no longer valid references
				for (int j = 0; j < a; j++)
				{
					((Stats)stats).existingUnits[i]++;
				} 
			}
		}	
	}

Before Unit Training

Max population size in the below screenshot is 100, meanwhile total army size is 0 and total population size is also 0.

301

Menu stats before units trained

After Unit Training

407

HUD after training 19 new units

Menu stats have been adjusted. We still have the same max army capacity (that only increases if you add a building that can store soldier units -- see Shop Menu > Military Buildings) but now we have 19 total army units for a total population size of 49. This is different because some units carry a population size greater than 1. Read more details below.

Item in Image AboveDescription
Max Army CapacityThis is the maximum capacity of the player army. The default is 100 set in the GameManager Stats Inspector. The only way it can be increased is if your have buildings with StoreType = Soldiers. Reach the Shop Menu > Military Buildings section for more details or see the Tatami item included in the City Building Kit Demo.
Actual Total of UnitsThis is the total number of units. If your game has units that take more than one population space per unit, this number will be different (e.g. 19) than the total population (e.g. 49 as seen in the image above)
Total Army SizeSome units like the archer take 1 population space. Heavy units like the viking take 3 population space. That's why the total for 19 units can be 49/100 of your army capacity. More details about unit weights below

How do I expand my army max capacity?

You can read more about this in the Shop Menu > Military Buildings section, however here's a brief summary. Some buildings in your game can increase your total soldier unit population. In the City Building Kit example we provide one of them for you to try. Look at the XML/Buildings.xml Tatami building.

757

Military buildings can increase population size. Click to view larger.

Other than resource generators and storage buildings - you can also store units in your structure to give the player a bigger maximum army size. The XML sections in Shop Menu > Military Buildings describes more about this.

304

Maximum army size in the HUD, increasable with buildings in your game that store units

Unit.xml Example

Here's an example of one of the unit XML items included in the City Building Kit XML/Units.xml The most important item in this list to observe is that the StoreType is Distributed and StoreResource is set to Soldiers.

<Unit>			
		<Name>Green Alien</Name>
    <!--  name displayed in the store -->			
    
		<UnitType>Alien</UnitType>
    <!--  IMPORTANT: this same as prefab - instead of clutting the labels list you set the prefab name here in the XML. Prettier right? -->	
    
		<Description>A smelly alien, green with envy. Maybe it's something he ate?</Description>
    <!--  description displayed in the store -->	

		<Currency>Mana</Currency>
    <!-- either Gold, Mana, or Crystals to buy -->		
    
		<Price>50</Price>
    <!-- amount of resource necessary to pay for the unit-->
    
		<TimeToBuild>1</TimeToBuild>
    <!-- the time (in minutes) needed to create the unit -->

		<Life>200</Life>
    <!-- HP of this unit -->
    
		<Size>1</Size>
    <!--how many population slots the unit occupies-->
    <!--by default it is 1, but you can increase this like 3, 5, 10, etc. -->

		<XpAward>100</XpAward>
    <!-- experience awarded for the completion of an object -->
	</Unit>

A closer look at building XML

If you look closely in the above XML, you'll see the green alien character costs 50 of of the Mana currency. You could use whatever currency you want in your game, in the demo we have two placeholders called Gold and Mana. (Plus one rare currency called Crystal Gems)

<Currency>Mana</Currency>						
		<Price>50</Price>

Units also get a population size. In the example above it's 1.

<Size>1</Size>

Size could be any integer value as long as it's less than your army max capacity. For example, you could have 15 archers with a population weight of 1 each or 5 vikings who each have a population weight of 3 for a total army size of 15 (Total unit count is less in the latter, and larger in the former army size).

This is incredibly useful for building games with heavy units like tanks, horses, or heros who may have a huge HP value of 1,000 but take an incredible 10 or 15 population space per unit. Population space is one way that adds extra strategy to your gameplay.

Also, for units, like defense structures and buildings they need an HP health value for battle. You can enter whatever value you want (integer), by default we use 200.

<Life>200</Life>

As of the 6.0 version release, the Life value is not used in the development copy but instead life is hardcoded into the Scripts/Units/FighterController.cs file as seen below:

// excerpt from FighterController.cs
private int maxLife = 100,//for progress bar percentage
		curPathIndex;

Calculation of hit damage from buildings is done further in Scripts/Units/FighterController.cs where each hit takes 25 HP away from maxLife. If life is == 0, the unit is terminated from gameplay.

// Excerpt from FighterController.cs
// Function calculates attack damage and death of units
public void Hit()
	{
		if (life >= 25) 
		{
			life -= 25;
			((tk2dUIProgressBar)healthBar).Value = (float)life / (float)maxLife;

			if(life == 0)
			Destroy (this.gameObject);//, 0.5f
		} 			
	}

Another XML example for Units

<Unit>			
		<Name>Viking</Name>		
		<UnitType>Viking</UnitType>					
		<Description>The antlers are sold separately. The beard is just a fasion statement.</Description>

		<Currency>Mana</Currency>						
		<Price>200</Price>							
		<TimeToBuild>1</TimeToBuild>				

		<Life>5000</Life>							
		<Size>4</Size> 								

		<XpAward>100</XpAward>					
	</Unit>

You'll notice the only major change is that Life is larger and population Size is 4 times as much.

MenuUnit.cs - Where the XML is loaded into

In Scripts/Units/MenuUnit.cs the soldier data from your XML file (seen above) is loaded using a common system used also for all other buildings. Here's an excerpt from MenuUnit.cs of the XML data load:

//reads structures XML
public void GetUnitsXML()
	{

		XmlDocument xmlDoc = new XmlDocument(); 
		xmlDoc.LoadXml(UnitsXML.text); 
		XmlNodeList unitsList = xmlDoc.GetElementsByTagName("Unit");
			
			foreach (XmlNode unitInfo in unitsList)
			{
			XmlNodeList unitsContent = unitInfo.ChildNodes;	
				dictionary = new Dictionary<string, string>();

				foreach (XmlNode unitItems in unitsContent) 
				{
      // For each of the XML values, it stores the information
      // to be used later in BaseCreator.cs
				
				if(unitItems.Name == "Name")
				{
					dictionary.Add("Name",unitItems.InnerText); 
				}	
				if(unitItems.Name == "UnitType")
				{
					dictionary.Add("UnitType",unitItems.InnerText); 
				}	
				if (unitItems.Name == "Description") 
				{
					dictionary.Add ("Description", unitItems.InnerText); 
				}
				if(unitItems.Name == "Currency")
				{
					dictionary.Add("Currency",unitItems.InnerText); 
				}	
				if(unitItems.Name == "Price")
				{
					dictionary.Add("Price",unitItems.InnerText); 
				}
				if(unitItems.Name == "TimeToBuild")
				{
					dictionary.Add("TimeToBuild",unitItems.InnerText); 
				}
				if(unitItems.Name == "Life")
				{
					dictionary.Add("Life",unitItems.InnerText); 
				}	
				if(unitItems.Name == "Size")
				{
					dictionary.Add("Size",unitItems.InnerText); 
				}	
				if(unitItems.Name == "XpAward")
				{
					dictionary.Add("XpAward",unitItems.InnerText); 
				}
          
      // The following two are not currently used in the demo
      // but have been provided for developers wishing to expand
      // their builings with upgrades. Additional scripting required.
      
				if(unitItems.Name == "Upgrades")
				{
					dictionary.Add("Upgrades",unitItems.InnerText); 
				}
				if(unitItems.Name == "UpRatio")
				{
					dictionary.Add("UpRatio",unitItems.InnerText); 
				}
				}
				units.Add(dictionary);
			}
		
	}

What happens when the buy button is clicked for a unit?

When the player clicks one of the buttons to train the first unit listed in the store, this function is triggered:

//receive a NGUI button message to build
	public void OnBuild0()	{ VerifyConditions(0);  }
//when a unit training menu button is pressed

VerifyConditions() is run shortly after, which initiates the conditions checking to see if the player actually can train

VerifyConditions()

Can the player train this unit? In Scripts/Units/MenuUnit.cs the VerifyConditions() script takes over once the store button has been pushed to determine if the following conditions are met and canBuild is set to true.

VerifyConditions() Test #1 - Do they have enough funds?

The first test the player data must pass is their funds - do they have enough of the currency the unit requires to be trained?

// Get the unit cost
int price = int.Parse (units [currentSelection] ["Price"]);

// If the unit cost is in Gold, do they have enough gold?
if(units [currentSelection] ["Currency"] == "Gold")//this is string, not boolean 
{
	// Finding out how much gold they have remaning if you subtract it
	if(!((Stats)stats).EnoughGold(price))
	{				
		canBuild = false;
		((Messenger)statusMsg).DisplayMessage("Insufficient gold.");				
	}
  
// Repeat the same above, but instead for the other currency (Mana)
}
else if(units [currentSelection] ["Currency"] == "Mana")
{
	if(!((Stats)stats).EnoughMana(price))
	{
		canBuild = false;
		((Messenger)statusMsg).DisplayMessage("Insufficient mana.");
	}
  
// Repeat the same above but for the rare Crystal currency
// If you have additional currencies in your game, uncomment the //
// and repeat for each currency
}
else //if(units [currentSelection] ["Currency"] == "Crystals") - if you want to have units sold with crystals
{
	if(!((Stats)stats).EnoughCrystals(price))
	{
		canBuild = false;
		((Messenger)statusMsg).DisplayMessage("Insufficient crystals.");
	}
}

VerifyConditions() Test #2 - More than 10 units of the same type in the training queue?

In the City Building Kit each type of unit can have a maximum of 10 in the training queue at once. You can adjust this value simply by changing this section here.

// more than 10 units of this same type already in the training queue?
if(trainingIndexes[currentSelection] == 10)
{
	canBuild = false;
	((Messenger)statusMsg).DisplayMessage("10 units limit.");
}

VerifyConditions() Test #3 - Check army population capacity

The last test to pass before units can be deployed is if the player's total unit population has been reached. This test ensures the player can't build more units than they can house.

// Have enough space left in your army population capacity?
if(((Stats)stats).occupiedHousing + 
   int.Parse (units [currentSelection] ["Size"])>
   ((Stats)stats).maxHousing)
{
	canBuild = false;
	((Messenger)statusMsg).DisplayMessage("Increase your soldier housing capacity.");
}

VerifyConditions() - If all tests pass, greenlight training.

If the player's data passes all 3 tests and canBuild still is set to true, then the script adjusts the player data awarding the XP they get from the building XML (if any) and deducting the costs involved from the building currency and price.

if (canBuild) 
{			
	// Subtract the amount of the unit they want to build from their stats
  // Pay is a function in the MenuUnit.cs that runs the Stats script function to substract resources
  // ((Stats)stats).SubstractResources (gold, mana, crystals); 
	if(units [currentSelection] ["Currency"] == "Gold")
	{	
		Pay (price, 0, 0); 
	}
	else if(units [currentSelection] ["Currency"] == "Mana")
	{
		Pay (0, price, 0); 
	}
	else //if(units [currentSelection] ["Currency"] == "Crystals")
	{
		((Stats)stats).crystals -= int.Parse (units [currentSelection] ["Price"]);
		Pay (0, 0, price); 
	}

	((Stats)stats).experience += int.Parse (units [currentSelection] ["XpAward"]);
	if(((Stats)stats).experience>((Stats)stats).maxExperience)
	((Stats)stats).experience=((Stats)stats).maxExperience;

	((Stats)stats).occupiedHousing += int.Parse (units [currentSelection] ["Size"]);
	// Update the player's stats UI to reflect the new experience and loss of resources
	((Stats)stats).UpdateUI();
  
  // Start the training of the unit
  // This is a function that manages the array of units in the training queue
  // Before they're assigned to the player's population stats
	Build (currentSelection);
}