XP and Levels

👍

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.

429

Levels HUD screenshot. Click to view closer.

What is XP?

XP (also known as Experience Points) are what most games use to track player progress in addition to unlocking higher levels. In the City Building Complete Kit you can use levels to limit the number of structures your players can build of a certain type, like caps on total gold mines or defense structures: two cannons max at level 1, three cannons max at level 2, five cannons max at level 3 and so on...

For unrestricted building limits, test at Level 11

Open the Stats GameManager and set the Level to 11 as seen in the screenshot below when testing to access the unrestricted developer test level. You can build 100 of each building on this level, earlier sample levels 0-10 have limits restrictions for the number of certain buildings you can build until you increase your level.

Why do we do this? This way you have examples for how to do this in the kit, but also an easy way to test your game without restrictions. Make sure to remove Level 11 from the Evolution.xml before you release your game unless you really want 100 structure limits.

1426

Level 11, the debugging demo level for developers. Click to view larger.

Where do we edit XP Levels?

Open XML/EvolutionBuildings.xml to see the data for XP levels in the demo.

EvolutionBuildings.xml

All the level data is stored in XML/EvolutionBuildings.xml (or Evolution.xml)

In this XML file you will see an example level at the top with comments. A copy of this is below with additional comments for your reference.

<Level>	<!-- 00 -->
		<MaxBuildings>1,2,2,1,1,1,1,1,1,1,1,1</MaxBuildings>			
    <!-- max number of buildings - includes all, production and army -->
    <!-- total array objects match Buildings.xml 12 elements -->
		<MaxWeapons>1,1,1,1,1,1</MaxWeapons>
    <!-- max number of weapons -->			
    <!-- total array objects match Weapons.xml 6 elements  -->		
		<MaxWalls>25,25</MaxWalls>
    <!-- max number of walls -->	
    <!-- total array objects match Walls.xml 2 elements  -->	
		<MaxAmbients>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</MaxAmbients>
    <!-- max number of ambient elements -->				
    <!-- total array objects match Ambient.xml 15 elements -->	
	</Level>

There are 4 elements of your game you can limit the maximum number per level:

Level Max Objects
Buildings - for example one gold mine for level 1, three for level 2, five for level 3, and so on ....
Weapons - for example two cannons max at level 1, three cannons max at level 2, five cannons max at level 3 and so on...
Walls - for example ten wood walls max at level 1, twenty wood walls max at level 2, thirty wood walls and ten stone walls max at level 3, and so on...
Decorations - however you design, could follow the same as buildings. Decorations are not attacked in battle and you can charge whatever currency for them (even in-app purchase gems)

Level XML Examples

<Level>	<!-- Player Base Level 01 -->
		<MaxBuildings>2,2,2,1,1,1,1,1,1,1,1,1</MaxBuildings>	
		<MaxWeapons>2,2,2,1,1,1</MaxWeapons>							
		<MaxWalls>50,50</MaxWalls>	
		<MaxAmbients>2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2</MaxAmbients>							
	</Level>
  
	<Level>	<!-- Player Base Level 02 -->
		<MaxBuildings>3,3,3,1,1,1,1,1,1,1,1,1</MaxBuildings>	
		<MaxWeapons>2,2,2,2,2,2</MaxWeapons>							
		<MaxWalls>75,75</MaxWalls>	
		<MaxAmbients>3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3</MaxAmbients>				
	</Level>
  
	<Level>	<!-- Player Base Level 03 -->
		<MaxBuildings>4,3,3,1,1,1,1,1,1,1,1,1</MaxBuildings>	
		<MaxWeapons>3,3,3,2,2,2</MaxWeapons>							
		<MaxWalls>100,100</MaxWalls>	
		<MaxAmbients>4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4</MaxAmbients>				
	</Level>

How are level limitations used in the store?

These XP level limitations are used by the UpdateLabelStats() function in the Scripts/Creators/BaseCreator.cs script. This function changes the labels in the store depending on different problems, such as not enough currency or in this case - your current level restricts the building limit and you've reached that limit.

In the below images from the store, you can see in the first example image we can still build the item in the store as we have build 0/2 of the gold forge. The button and store item looks normal.

149

Can still purchase gold forges, level limit not yet reached.

However in the second example, the text in the store item shows 2/2 in the corner, which means for our current level we can only have a maximum of 2 gold forges and we've already created these. The store item turns grey and the button text black.

Clicking the button returns an error that your XP level needs to be higher (read the next section below for how to award XP points to your player - we already have setup a few examples like training units, building other structures, or removing trees and objects on the map)

161

Level limit reached (2/2 gold forges), the store item turns grey and cannot be purchased.

The following code reference is an excerpt from Scripts/Creators/BaseCreator.cs showing the function that updates the label stats with the changes we saw in the above images.

// Scripts/Creators/BaseCreator.cs
// UpdateLabelStats() changes the store label pricing from the XML values
// in addition to changing the button functions depending if the player
// has the money to buy or their XP level restricts the number of buildings

	protected IEnumerator UpdateLabelStats()
	{
    // Wait for a small period to let the XML load
		yield return new WaitForSeconds (xmlLoadDelay);

    // Get an update to the structures allowed 
		UpdateStructuresAllowed ();
    
    // Colors for different issues
    // Black = XP level limit exceeded, can't build this structure
    // Brown = Normal, all is fine.
    // Red = Not enough of the currency to purchase
    
		Color 
		black = new Color (0, 0, 0),
		brown = new Color (0.45f, 0.09f, 0),
		red = new Color (1, 0, 0);

		bool buildingAllowed;	

    // Loop through all of the structures in the game
		for (int i = 0; i < totalStructures; i++) 
		{
      // Check if the building can still be created
			buildingAllowed =(allowedStructures[i]-existingStructures[i]>0);

      // Get label details
			NameLbs[i].text = structures [i] ["Name"];
			TimeLbs[i].text = structures [i] ["TimeToBuild"];

			QuantityLbs[i].text =  existingStructures[i].ToString()+"/"+allowedStructures[i].ToString();
			PriceLbs[i].text = structures [i] ["Price"];

      // If the building is allowed 
      // (haven't exceeded XP level limits for this structure)
			if(buildingAllowed)
			{
        // Normal background blue graphic
        // And text colors
				NicheSprites[i].spriteName = "stone_niche";
				PortraitSprites[i].atlas = Portraits;

				NameLbs[i].color = brown;
				TimeLbs[i].color = brown;
				QuantityLbs[i].color = brown;
				PriceLbs[i].color = brown;
			}
			else
			{
        // Exceeded level limits, so turn the background grey
        // and the text black
				NicheSprites[i].spriteName = "stone_niche_bw";
				PortraitSprites[i].atlas = PortraitsBW;

				NameLbs[i].color = black;
				TimeLbs[i].color = black;
				QuantityLbs[i].color = black;
				PriceLbs[i].color = black;
			}	

			bool hasMoney = false;

      // Checks if they have enough of the currency the sturcture costs
			if (structures [i] ["Currency"] == "Gold")
			{
				if(((Stats)stats).gold + ((Stats)stats).deltaGoldPlus - ((Stats)stats).deltaGoldMinus >= int.Parse(structures [i] ["Price"]))
				{
					hasMoney = true;
				}
			} 
			else if (structures [i] ["Currency"] == "Mana")
			{
				if(((Stats)stats).mana + ((Stats)stats).deltaManaPlus - ((Stats)stats).deltaManaMinus>=int.Parse(structures [i] ["Price"]))
				{
					hasMoney = true;
				}
			}
			else //if (structures [currentSelection] ["Currency"] == "Crystals")
			{
				if(((Stats)stats).crystals +((Stats)stats).deltaCrystalsPlus-((Stats)stats).deltaCrystalsMinus>=int.Parse(structures [i] ["Price"]))
				{
					hasMoney = true;
				}	
			}

      // If they don't have the money, but the building is
      // allowed (not limited by XP) then change the text color
      // to red. Clicking the button will show a text error
      // (Another function handles this in the BaseCreator.cs script)
			if(!hasMoney && buildingAllowed)
			{
				((UILabel)PriceLbs[i]).color = red;
			}
		}
	}

How to award XP points to your players

There are a few different scripts. Search for XPAward or experience in the Scripts folder to locate the references in scripts. Below are a few references to the XPAward element in each of the XML files.

Gain XP Points creating Buildings, Weapons, Walls

Buildings.xml, Weapons.xml, Walls.xml -- these all include an element which you can use to award players with a certain amount of XP when they create their buildings.

For example, in Buildings.xml, creating a gold forge mine gives the player 100 XP each time.

<Building> <!-- 01 -->		
		<Name>Gold Forge</Name>	
		<StructureType>Forge</StructureType>	
		<Description>Gold mines are so '2050s. Mages create gold by simply mumbling to themselves. Or pull it out of their, aaa... pointy hats! We never asked. Neither should you. Know your place, little one.</Description>
								
		<Currency>Mana</Currency>						
		<Price>100</Price>						
		
		<ProdType>Gold</ProdType>	
		<ProdPerHour>100</ProdPerHour>	

		<StoreType>Internal</StoreType>					
		<StoreResource>Gold</StoreResource>			
		<StoreCap>500</StoreCap>		
						
		<TimeToBuild>10</TimeToBuild>				
		<Life>300</Life>							
		<XpAward>100</XpAward>		
  
		<Upgrades>30</Upgrades>	
		<UpRatio>2</UpRatio>
		
	</Building>

For example, in Walls.xml, building one stone corner tower gives the player 2 XP per segment.

<Wall>
		<Name>Stone Tower</Name>	
		<Currency>Gold</Currency>				
		<Price>400</Price>
		<TimeToBuild>0</TimeToBuild>
		<Life>400</Life>
		<XpAward>2</XpAward>
		<Upgrades>0</Upgrades>				
		<UpRatio>0</UpRatio>				
	</Wall>

For example, in Weapons.xml, creating an archer tower gives the player 100 XP each time.

<Weapon>
		<Name>Archer Tower</Name>		
		<Description>Ranged.</Description>	
									
		<Currency>Gold</Currency>					
		<Price>100</Price>												
				
		<TimeToBuild>30</TimeToBuild>				

		<DamagePerSecond>25</DamagePerSecond>
		<Life>200</Life>							
		<Range>50</Range>
		<FireRate>2</FireRate>						
		<DamageType>Single</DamageType>				
		<TargetType>Dual</TargetType>				
		<PreferredTarget>Any</PreferredTarget>		
		<DamageBonus>0</DamageBonus>				

		<XpAward>100</XpAward>						
		<Upgrades>0</Upgrades>							
		<UpRatio>0</UpRatio>												
	</Weapon>

Gain XP Points Training Units

Players can also get XP points training units. If you don't want to offer this, change the value to 0.

For example, in Units.xml, creating an archer gives the player 100 XP.

<Unit>			
		<Name>Archer</Name>		
		<UnitType>Archer</UnitType>					
		<Description>Enchanted forest's finest.</Description>

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

		<Life>200</Life>							
		<Size>1</Size> 								

		<XpAward>100</XpAward>						
		<Upgrades>0</Upgrades>							
		<UpRatio>0</UpRatio>						
	</Unit>

Gain XP Points from Removing Terrain Objects

Also, your game players can get XP by removing terrain objects. Like all the other XML files, we make this easy to change.

904

Visual example of gaining 2 XP from removing a random terrain object called ClamC. Click to view larger.

For example, in Removables.xml, removing one of the random TreeA objects awards the player 2 XP.

<Removable>
		<Name>TreeA</Name>		
		<RemoveTime>5</RemoveTime>
		<Currency>Mana</Currency>				
		<RemovePrice>100</RemovePrice>
		<XpAward>2</XpAward>
	</Removable>

Adjust the actions Scripts/Creators/Removables/RemovableTimerSelector.cs

//Adds the xpAward value to the player stats.
((Stats)stats).experience += xpAward;	

GameObject gainExperienceIco = (GameObject)Instantiate(GainExperience,transform.position+new Vector3(-50,0,0), Quaternion.identity);

gainExperienceIco.GetComponent<FadeOutGain> ().SetValue (xpAward);

Setting a Starting Level for Testing

Open the Game scene and in the hierarchy, select Game Manager > Stats. On the right side inspector you can change the Level from 1 (default) to any number. Save and play the scene.

238

Select Stats. Click to view larger.

299

Edit the starting level and experience. Click to view larger.

How is XP updated in the menu bar?

Look for UpdateUI in Scripts/Menus/Stats.cs. This adjusts the UISlider value for the experience, sets the Player name (right now just a placeholder) and also the current level plus text values for the experience.

public void UpdateUI()//updates numbers and progress bars
	{
    // Red slider, tracking progress of the XP
		((UISlider)xpBar.GetComponent ("UISlider")).value = (float)experience/(float)maxExperience;
    
    // Player name label above XP bar, hardcoded by default for testing
		nameLb.text = "Player Name";
    
    // The XP level number to the left of the XP amount
		levelLb.text = level.ToString ();

    // The text above the UISlider that says something like 100 / 9999
		xpLb.text = experience.ToString () + " / " + maxExperience.ToString();
   
    // ......

📘

Remember to call ((Stats)stats).UpdateUI(); when done updating any stats

The kit is optimized so that UI updates are not made without purpose. If you ever update the stats in any of your scripting - make sure to add ((Stats)stats).UpdateUI(); at the end to make sure your changes are visible.

How is player XP saved and loaded when the game closes?

Like other player stats - XP is saved and loaded from Player data in the Scripts/Save files. By default, this is manual in the game settings panel until you activate automatic savings (see documentation page in Game Settings section)