Auto save and auto load on quit app.
Hello, everybody!
I'm quite new around this place, and kinda newbie, so I'd appreciate if you are patient with me :).
I'm working on a project where the only goal is to tap an object with your finger. Yep, that's it. It's gonna be for android and there's gonna be a counter whenever you tap on it. That's already been done, the problem comes when I think about how to make the game save those numbers automatically when the user quits the app and how to make the game auto-load whenever he enters again. I've been searching through the forum, but I couldn't get anything clear. I've seen something about "Serialization" and "OnApplicationQuit" but, honestly, I don't know how to make it work or where to attach them to.
I'm gonna paste my code here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Click : MonoBehaviour
{
public UnityEngine.UI.Text oroPuntos;
public int gold = 0;
public int goldClick = 1;
public int counter = 0;
void Update () {
goldPoints.text = "gold: " + gold;
}
public void Clicked(){
gold += goldClick;
//gold = gold + goldCick;
counter ++;
if (counter == 10)
{
gold = gold + 100;
}
if (counter == 11)
{
goldClick = goldClick + 1;
}
}
}
I made a Canvas, so everything is inside of it. It's a 2D game, btw.
Thank you!,
N.
Answer by herDev · Mar 21, 2017 at 10:29 AM
Hi! You can use PlayerPrefs to save and load data:
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
In your case, you can use SetInt to save the data at the approriate time. For example:
PlayerPrefs.SetInt("goldValue", gold);
GetInt can be called when the app is started, to retrieve the saved value:
gold = PlayerPrefs.GetInt("goldValue"));
Just one note, PlayerPrefs literally creates a text file on the device that users can navigate to through a file browser and modify. If you need the value to be secure, there are some of posts in Unity Forums with some ideas.
Hope that helps!
Your answer
![](https://koobas.hobune.stream/wayback/20220612113627im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Save instances and recognize them on load 0 Answers
Can someone tell me what is wrong with this script? 1 Answer
Cannot Convert from NewGame to CubeAI 0 Answers
Convert int to binary 1 Answer
Unexpected duplication of scene 1 Answer