hello everyone. I have two variables in my game. One is for Score and the other is for coin that’s defined through UI Text. I want to save number of coins collecting by player. I failed to save and load. here is my script;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIManager2 : MonoBehaviour {
public static int coin_score = 0;
public Text coin_text;
void Start () {
}
// Update is called once per frame
void Update () {
coin_text.text = coin_score.ToString ();
}
}
Something like this should work:
void Start()
{
coin_score = PlayerPrefs.GetInt("anyNameYouLike") //Load value
}
void Update()
{
coin_text.text = coin_score.ToString();
PlayerPrefs.SetInt("anyNameYouLike", coin_score); //Save value
}
You can save a string (PlayerPrefs.SetString(“name”, stringToSave)), but I do not recommend it in this case. Saving the int is much easier. Also I would recommend updating the score only when it is modified.
I’m new in unity
Your code worked fine but when I try to buy a new item, My coin number doesn’t change. I wrote a code in which for any item to buy, number of coins must be decreased. It worked fine before, But now It fails. Should I put your code in Awake ()?
@azerty0220pl