- Home /
player prefs
hehoo all,
i have just 1 simple question, i couldnt find any answer for..
when i try to use my playerprefs like this:
public int gold;
void Start () {
PlayerPrefs.SetInt("Gold", 25);
print(gold);
gold = PlayerPrefs.GetInt("Gold");
PlayerPrefs.SetInt("Gold", gold*2);
print(gold);
}
when i start it, it prints me 0 and 25. shouldnt it print 25 and 50?? and how it comes it shows first 0 everytime i start the game? i set it to 25 with the last time?
this one have the same issue:
gold = PlayerPrefs.GetInt("Gold");
print(gold);
PlayerPrefs.SetInt("Gold", gold*2);
print(gold);
printing 2 times the same value
Answer by Necrohunter · May 21, 2018 at 10:11 PM
okay.. i have another question to this one:
how can i say in 1 script, that i have in the playerprefs 1234 Gold units and from another script add +100 gold?
its just not working, i dont get it..
Answer by Bunny83 · May 21, 2018 at 10:19 PM
Your problem is that the value stored in the playerprefs has no connection to your variable "gold". When you write a value to the playerprefs it won't affect your gold variable. In this snippet you actually set the playerpref value to two times the value stored in gold, but this won't change the value of your gold variable:
PlayerPrefs.SetInt("Gold", gold*2);
print(gold);
If you want to use playerprefs to store the latest gold value you should:
actually change your gold variable
Call SetInt after each change to the gold variable and simply store the current gold in the playerprefs
In Start you would re-initialize the gold variable at the beginning with the stored value by using GetInt
Note that GetInt has an optional second parameter which represents the default value if there hasn't been any value stored yet in the playerprefs. If you don't specify a default value, the value 0 is used.
I'm not sure what else we could say here as it's not clear what you want to do.
well, i am creating a simple mobile game where i have a gold value. everytime i make a match, i want to add an amount of gold. an the biggest problem is, i dont know how to add this amount to my gold units.
i tryed to say in other scripts: PlayerPrefs.SetInt("Gold", gold + 100); or PlayerPrefs.SetInt("Gold", + 100);
but im really not sure what i do wrong.. how can i access from another sripts to the main script where i coded the palyerprefs?
Your answer
Follow this Question
Related Questions
PlayerPrefs Storage Location on Android or iOS 4 Answers
Datasource for C# Android game 0 Answers
Read PlayerPrefs in Start()? 1 Answer
Where to save player progress? 0 Answers