- Home /
How to save coins with PlayerPrefs
Hello,
I am trying to save coins in Unity but every time I hit play the coins strats from 0. The code from Script is this:
public class CoinsManager : MonoBehaviour {
Text coinsScore;
public static int coinAmount;
public static int coinsCount;
void Start ()
{
coinsCount = PlayerPrefs.GetInt("Coins");
}
void Update()
{
coinsCount += coinAmount;
coinsScore.text = "Coins: " + coinsCount;
PlayerPrefs.SetInt("Coins", coinsCount);
}
Thank you!
Answer by finlay_morrison · Oct 10, 2017 at 07:24 PM
Firstlygoing into playerprefs every frame is not a good idea, playerprefs takes quite a long time to acsess in computer terms (still in the order of milliseconds tho) Make sure you are using UnityEngine.UI , try using this code:
public class CoinsManager : MonoBehaviour {
Text coinsScore;
public static int coinAmount;
public static int coinsCount;
void Start ()
{
coinsCount = PlayerPrefs.GetInt("Coins");
}
void Update()
{
coinsCount += coinAmount;
coinsScore.text = "Coins: " + coinsCount;
}
void OnApplicationQuit() {
PlayerPrefs.SetInt("Coins", coinsCount);
}
It's not working. Do you know another method to save coins? Thank you.
Answer by Glurth · Oct 10, 2017 at 07:29 PM
public static int coinAmount;
Static variables are NOT serialized along with the rest of the monobehavior. The Static keyword means you want to have only one instance of the variable, for ALL instance of the containing class.
However, I suspect you really want to have a single CoinsManager class in the scene, (rather than what you have now, a single "coinAmount" for all CoinsManagers in the scene.)
Google "unity singletons" for how to make sure you have only one CoinsManager in a scene.
This way, you can make your public static int coinAmount;
NOT static: public int coinAmount;
and it WILL be serialized by unity.