I create buildings and they have child Text objects that will reflect the building level.
The Problem:
What can I use to store the buildings a player has built so the data can be persisted?
I've looked at Lists, but when I upgrade a building, how would I update the list so that particular building has its new level reflected?
I'm working on a dictionary so I can update the key with the new value (level) but running into a problem with the keys and names. If I have lets say 10 "Farms" and try to add them to the dictionary, even though they have different properties, I get an error that I have a duplicate.
Currently I am learning how to persist that data through scenes;
GameManager.CS
public class GameManager : MonoBehaviour
{
public static Dictionary<Building, int> playerBuilt = new Dictionary<Building, int>();
public void SaveState()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/EmpireGame", FileMode.Open);
SaveClass sc = new SaveClass()
{
food = Player.food.amount,
buildingList = playerBuilt
};
bf.Serialize(file, sc);
file.Close();
}
}
[Serializable]
class SaveClass
{
public int food, wood, iron, stone;
public Dictionary<Building, int> buildingList = new Dictionary<Building, int>();
}
Building.CS
public abstract class Building : MonoBehaviour, IUpgradable {
public int ID;
//level this building is
public Text levelText;
public int level = 0;
//starting cost to amplify the upgrade cost
public int foodBase, woodBase, ironBase, stoneBase;
//Upgrade cost
public int foodCost, woodCost, ironCost, stoneCost;
public float BuildingCostPercentage = 5f;
public void UpdateDictionary()
{
if (GameManager.playerBuilt.ContainsKey(this))
GameManager.playerBuilt[this] = level;
else
GameManager.playerBuilt.Add(this, level);
}
}
Note: I have not tested the save function so I expect errors.