-1

I have a variable which I want to save the data to the user's device. Ex: float score = 100;

I want to save this variable as data and load it on game run.

Mintvbz
  • 15
  • 2

1 Answers1

0

You can store your data in a external file like a json. When you want to access your data to edit or just get the value, you can simply read/write it from the file

I advise you to use the library Newtonsoft.

Once you have downloaded the packages, add the following usings :

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

You can use this code to write in the file

/////Write in the file/////

//Create a dynamic object to store data
dynamic obj = new JObject();

//Set the values
obj.WorkDuration = workDuration;
obj.PauseDuration = pauseDuration;
obj.NbSessions = nbSessions;

//Write the values in the json file
File.WriteAllText(JsonFileFullname, JsonConvert.SerializeObject(obj));

And this code to get the data in the file

/////Get values from the file/////

//Create a reader object for get the content of the json file
StreamReader reader = new StreamReader(JsonFileFullname);

//Read the content of the json file
string json = reader.ReadToEnd();

//Create a dynamic object with stored data
dynamic data = JObject.Parse(json);

//Get the values
int workDuration = data.WorkDuration;
int pauseDuration = data.PauseDuration;
int nbSessions= data.NbSessions;

Your JSON file should look something like this

{"WorkDuration":300,"PauseDuration":5,"NbSessions":8}

I hope my answer will be of use to you. If you have any questions, don't hesitate to ask them

karma
  • 1
  • 1