- Home /
Adding Value to Already Saved Values
I have this set up so that it saves the Coins Collected value and the loads it in another scene. Ill attach the two scripts below...What i want to do now is so the ObjectDestroy class will save its value as Save_Coins_Collected but when it saves the value, I want to add this to the previously saved value which would be loaded in the Upgrades_Script as TotalCoinsCollected. This will then be so the player collects coins and if they play again or close game and then play later, it will add the coins to there previous amount of coins. The coins will build up and allow them to buy things in game.
ObjectDestroy.cs
void OnTriggerEnter(Collider other) //When a named trigger is entered...do something
{
if (other.tag == "ObjectDestroy")
{
Debug.Log ("HITTTTTTTTT"); //display in console if object hits the ObjectDestroy tag
Destroy (gameObject); // destroy object this script is attached to
}
if (other.tag == "Player")
{
Lives_2.Lives_Left --;
Time.timeScale = 0; // stop the game if player tag is hit
CoinsCollected.Coins_Collected = PlayerPrefs.GetInt ("Coins");
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create (Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData();
data.Save_Coins_Collected = CoinsCollected.Coins_Collected;
bf.Serialize (file, data);
file.Close();
Application.LoadLevel ("Lose_Screen"); //Load Lose_Screen scene
}
}
}
[Serializable]
class PlayerData
{
public int Save_Coins_Collected;
}
Upgrades_Script.cs
{
public static int TotalCoinsCollected;
Text text;
void Awake()
{
text = GetComponent<Text> ();
}
// Use this for initialization
void Start ()
{
if (File.Exists (Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
TotalCoinsCollected = data.Save_Coins_Collected;
}
text.text = "Total Coins Collected: " + TotalCoinsCollected;
}
}
Any Help Appreciated.
At the moment the coins collected is saved and can be loaded...but everytime the player plays the game and collects more coins, the coins collected value gets saved as this new value...weere as i want the new value to be added to the older saved value... $$anonymous$$g Player plays 1st time...Coins collected is 4 (this value is saved) Player plays 2nd time...Coins collected is 1 --> this value replaces the value of 4 in the previous play attempt...i want them to be added so it will equal 5...the new saved value will be 5...next time player plays they get 3...adds onto the 5 and is saved to be new value of 8 and so on ?
Answer by Morgan · May 22, 2015 at 05:47 PM
Load the old value, add the new one (stored in some variable) to it, then save the resulting sum.