- Home /
How to save data in game and display it?
I'm making a game using c# and I want to be able to save the stats (score, time etc...) and to be able to display it in the end of the game, when the player loose or in stats category. I know there is option of the "PlayerPrefs", but I couldn't find tutorials that explain how to use it with c#.
Answer by fifthknotch · Mar 09, 2014 at 06:56 AM
The docs have short examples that work in either JS or C#:
http://docs.unity3d.com/Documentation/ScriptReference/PlayerPrefs.html
The syntax for this is the same on whatever language you prefer. here is an example video:
http://cgcookie.com/unity/2012/09/10/playerprefs/
I believe his code is in JS (It's been awhile since i watched the video) but the PlayerPref part should be able to be carried over to C# just fine. Just change the variable declarations to fit C#'s format.
Answer by NoodleSpenny · Mar 09, 2014 at 03:38 PM
As fifthnotch said, there are simple examples in C# on the script reference pages for PlayerPrefs methods.
If you want to save an integer score to PlayerPrefs:
PlayerPrefs.SetInt("Player Score", 10);
To retrieve an integer score from PlayerPrefs:
int score = PlayerPrefs.GetInt("Player Score");
If you just want to know if a value has ever been set for a key:
bool hasSavedScore = PlayerPrefs.HasKey("Player Score");
There are corresponding methods for float and string values as well.
Note that the PlayerPrefs is only persisted when the game quits -- this means that if your game crashes, the preferences won't be saved. You might want to periodically call PlayerPrefs.Save()
at appropriate times.
Answer by Monkeybrains · Mar 09, 2014 at 03:48 PM
Mike Geig(?) did an excellent video on saving data as part of the unity live training series:
[https://www.youtube.com/watch?v=J6FfcJpbPXE][1]
Your answer
![](https://koobas.hobune.stream/wayback/20220613135756im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Mac OS X: Build crashes 1 Answer
UnitySerializer Only Saving one Game Problem 0 Answers
Flip over an object (smooth transition) 3 Answers