- Home /
Question by
$$anonymous$$ · Apr 24, 2015 at 07:55 AM ·
c#loadingsaving
C# PlayerPrefs not Work
Hello, I creating a Save/Load script using PlayerPrefs. But when I trigger Loading(); the gold variable will not restore. But in the Regestry is the correcrt Number (PS: Sorry for my English, I'm German)
Script:`using UnityEngine; using System.Collections;
public class SaveLoad : MonoBehaviour {
public static int gold = 0;
public bool loading;
public bool saving;
void Start()
{
gold = (int)InventoryManager.inventory.GetItems ("coin");
}
void Update()
{
if (loading)
{
Load();
}
if (saving)
{
Save();
}
//Debug.Log (PlayerPrefs.GetInt("Gold"));
}
void Save()
{
PlayerPrefs.SetInt("Gold", gold);
saving = false;
}
void Load()
{
print(PlayerPrefs.GetInt("Gold"));
gold = PlayerPrefs.GetInt("Gold");
Application.LoadLevel (1);
loading = false;
}
}`
Comment
Answer by YoungDeveloper · Apr 24, 2015 at 08:01 AM
You should not load or save anything in the update, as it runs every frame.
private void Start(){
if(PlayerPrefs.HasKey("Gold")){
Debug.Log("we have gold, loading..");
load();
Debug.Log("Gold:"+gold);
}
else{
Debug.Log("we dont have gold, adding 1 and saving.");
gold++;
save();
}
}
private void save(){
PlayerPrefs.SetInt("Gold", gold);
}
private void load(){
gold = PlayerPrefs.GetInt("Gold", 0); //gold will be 0 if key not found
}
Use DeleteAll to clear saved data on your local drive.