- Home /
Other
how to properly save an int value ?
hi..i have been trying to properly save an int value using serialization following unity's data persistance tutorial but i am unable to do so.Basically i have a static int value(TotalStars) in my level selection scene and each time any of the 3 if's statements that are in script of game scenes(levels) is true the value of TotalStars is incremented by 1.Well till here it works good,i can go to first level then if i win and come back to level selection i can see the value incremented But i want to save this value and load it when we again start the game which i am unable to do so.i dont know whether its unable to save the value or i am placing the save and load method at wrong places.I have tried various things but its not working .SO can anyone tell me am i doing it the write way and where i need to put the save and load methods so they automatically work? Here is the Script from level selection scene(i tried with and without singleton following the tutorial,though i dont think i needed it )
Have you tried insert Debug.Log lines to see what works and what doesn't? This should be the first step when trying to find errors.
yups at many places to check the value of total stars but no clue
Answer by tkati · Sep 11, 2016 at 06:54 PM
I don't see where you are incrementing, I see a lot of data swaps but no +1 or ++ on anything ....
as i mentioned in the question detail that the value is being increased in another script so you wont see it here.didnot thought it was important to add that script also but i will include that in my comment
void OnTriggerEnter2D (Collider2D Ball)
{
EndGame.SetActive (true);
WinStar.SetActive (true);
PlayerPrefs.SetInt ("Level" + CurrentLevel.ToString () + "_win", 1);
deactive ();
COuntAndTime ();
Level$$anonymous$$anager.TotalStars += 1;
Answer by AurimasBlazulionis · Sep 11, 2016 at 06:53 PM
I believe this is the error:
FileStream file = File.Create (Application.persistentDataPath + "/total.dat");
You should write it like this:
FileStream file = File.Open (Application.persistentDataPath + "/total.dat", FileMode.OpenOrCreate);
Because now you tell Unity to create a file over existing one. If this does not work, then I would suggest moving save and load to the class, have a class instance which would store the variable, and in save method, you would not need to create additional class. bf.Serialize (file, this);
would be enough.
Follow this Question
Related Questions
PlayerPrefs v. XML File for Saving Data? 1 Answer
How can I load in data for a derived type class from a CSV? 0 Answers
Save/Load Animation State of Instantiated Prefabs 0 Answers
Can't Serialize Color or Vector2 3 Answers
Serialization Location 1 Answer