Question by
sidotidavide · Feb 23, 2020 at 10:55 AM ·
unity 2dsaveload
PlayerPrefs Problem
Hello everyone! I am creating a simple 2D game and I just added a simple script to save how much coins the player take from a level and load it when the player go to next level and to display them on the screen. The problem is that if for example I take 20 coins in the level, when I go to the next level the coins displayed are 12 and not 20. I don't know why but these are the scripts:
This is attached to the player
using UnityEngine;
public class Movement : MonoBehaviour
{
public int coinValue = 1;
public int coins;
void Update ()
{
PlayerPrefs.SetInt ("valueOfCoins", coins);
PlayerPrefs.Save ();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Coin"))
{
Destroy(other.gameObject);
coins += 1;
ScoreManager.instance.ChangeScore(coinValue);
}
}
This is attached to a score gameObject
using UnityEngine;
using TMPro;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager instance;
public TextMeshProUGUI text;
int savedCoins;
// Start is called before the first frame update
void Start()
{
savedCoins = PlayerPrefs.GetInt("valueOfCoins");
text.text = " = " + savedCoins.ToString();
if (instance == null)
{
instance = this;
}
}
public void ChangeScore(int coinValue)
{
savedCoins += coinValue;
text.text = " = " + savedCoins.ToString();
}
}
Comment
Answer by sidotidavide · Feb 23, 2020 at 04:52 PM
Hey Guys thank you all but I just found the solution!
I just added
void Start ()
{
PlayerPrefs.GetInt("valueOfCoins");
}
in the first script and it worked!
Your answer