- Home /
How to use PlayerPrefs to activate game objects permanently?
Hello fam,
I am trying to create a simple trophy system within my game. I've managed to use PlayerPrefs to store data such as Integers for recording high scores etc. but I can't seem to figure out how to easily implement PlayerPrefs for activating a trophy game object. Can someone please give me a play by play on how to achieve this? I'm using C#. Thank you so much for anyone reading this.
Answer by Deeblock · Jul 11, 2018 at 06:13 AM
All you have to do is assign a "key" to each trophy game object. For example, if you have a trophy called "Winner", you can simply assign it in PlayerPrefs:
PlayerPrefs.SetInt("winnerTrophy", 1);
Since PlayerPrefs doesn't have booleans, we can use the integers 1 and 0 to represent true and false respectively. The integer is arbitrary; we only need the key to be stored in PlayerPrefs to check for trophies (i.e. only store trophies that have been activated in playerprefs).
Next, you would keep a list of trophies in either a ScriptableObject or a Monobehaviour Class with their key names. Thereafter, you would just use a simple for loop when the game starts:
for (int i = 0; i < trophiesList.Length; i++) {
if (PlayerPrefs.HasKey(trophiesList[i])) {
// Trophy is activated, you can do other things here
}
}
Thanks for your reply. I still cant get this to work, ID$$anonymous$$ why but this PlayerPrefs is super confusing to me. Is there a way you can explain this step by step in layman's terms?
What is the problem that you're encountering? PlayerPrefs is basically like a config file to store, as the name suggests, player preferences. Using it is very simple. It acts like a dictionary, meaning that it stores a $$anonymous$$ey-Value pair. The "key" points to the "value", meaning if you call the key, you will get the value.
PlayerPrefs can save three data types: Strings, floats and integers. These are the "values". Then, you will need a "key" to point to the value, which will always be a string. So you can have string,string or string, float or string, int.
Saving into PlayerPrefs is very simple. All you have to do is call:`PlayerPrefs.SetFloat($$anonymous$$ey, Value)`, replacing the "SetFloat" with "SetString" or "SetInt" depending on the value type you are trying to save.
Retrieving data from PlayerPrefs works the same way:`PlayerPrefs.GetFloat($$anonymous$$ey)`, replacing the "GetFloat" with "GetString" or "GetInt" respectively. Note here you are only putting the $$anonymous$$ey, beacuse the "key" points to the "value" you have stored.
Ok i see, thank you that makes total sense. I think because you cant store game objects I'm getting confused on how to use it to effectively turn objects on and off permanently. I see what you're saying though, and Im trying to use your example code. I think my problem is that I cant get my for loop to work properly and having trouble with my trophy list set up.