- Home /
How to store and add gold for the player ?
Hi i am trying to store and add the gold for the player every time he plays the game. Now i used this code but it doesnt seems to work as intended. To make this clear I want to store the gold earned in the level and then add it up with the gold earned before . public Text goldtxt; public Text score;
public class GoldAmount : MonoBehaviour
{
public Text goldtxt;
public Text score;
// Use this for initialization
void Start()
{
int cur_gold = PlayerPrefs.GetInt("Gold");
int gold = PlayerPrefs.GetInt("CurrentGold");
PlayerPrefs.SetInt("CurrentGold", cur_gold);
goldtxt.text = "Gold " + (cur_gold + gold);
int CurScore = PlayerPrefs.GetInt("Score");
score.text = "Last Score: " + CurScore;
}
}
Answer by Xarbrough · Mar 11, 2018 at 12:48 AM
You can try something like this:
public class GoldAmount : MonoBehaviour
{
public Text text;
private int gold;
private bool wasInitialized;
private const string key = "Gold";
private void OnEnable()
{
// When the game starts, load the saved gold amount.
// Make sure, nothing else modifies gold before this was called.
gold = PlayerPrefs.GetInt(key, 0);
wasInitialized = true;
}
private void OnDisable()
{
// When the game ends, save the gold amount.
PlayerPrefs.SetInt(key, gold);
// This could also go in OnDestroy or OnApplicationQuit
// Or somehwere else to manually save.
wasInitialized = false;
}
private void OnGoldChanged()
{
text.text = "Gold: " + gold.ToString();
}
public int Gold
{
get { return gold; }
set
{
if (wasInitialized == false)
{
Debug.LogError("Cannot set gold before initialization.");
return;
}
if (gold != value)
{
gold = value;
OnGoldChanged();
}
}
}
}
You should clearly define when gold is loaded, modified and saved. I would simply load the last saved amount in OnEnable and make sure, that we don't modify the gold before this point. After initialization, we can simply change the variable and once we are ready to save (e.g. user clicks a button or the app quits), we save (in e.g. OnDisable, OnDestroy, OnApplicationQuit, etc).
However, PlayerPrefs is not meant to store game save data such as gold and score values. It is meant for player preference (e.g. audio volume, difficulty-setting or other lightweight and non-security critical values).
There are other ways to save data, as shown in this Unity tutorial: Persistance - Saving and Loading Data
The process of saving data is also called "serialization". Commonly used are binary serialization (via the BinaryFormatter class from the .Net framework), JSON (e.g. Unity's JsonUtility class or plugins like Newtonsofts Json.NET) and XML.
Your answer
Follow this Question
Related Questions
Ingame Quality Settings not recognized 1 Answer
Unity 5 not using my Resolution Settings 2 Answers
Saving Post Processing as a graphic option 1 Answer
In Game Graphics/Resolution Options 2 Answers