Playerprefs problem in my script

This is my coin script:

public class CoinManager : MonoBehaviour
{
    public static CoinManager instance;
    public static int coinScore;
    public Text coinText;
    void Start()
    {
        coinText = GameObject.Find("Score").GetComponent<Text>();
        coinScore = PlayerPrefs.GetInt("CoinScore", coinScore);
    }
    // Update is called once per frame
    void Update()
    {
        ShowCount();
    }
    public void AddScore(int amount)
    {
        coinScore += amount;
        PlayerPrefs.SetInt("CoinScore", coinScore);
        coinText.text = coinScore.ToString();
    }
    public void ShowCount()
    {
        PlayerPrefs.GetInt("CoinScore", coinScore);
        coinText.text = PlayerPrefs.GetInt("CoinScore", coinScore).ToString();
        Debug.Log("Coin Count is: " + coinScore);
    }
}

Hey guys,

So for my game I decided to give my player a reward when he finishes the level. So basically , If he touches the gameObject with the tag “win”, then I give him 30 coins. The problem is that when I give him the 30 coins and I close the game and then turn

This is the script where I reward the player after touching the gameObject



public class PlayerController : MonoBehaviour
{
    public Rigidbody rb;
    public AudioClip jumpingOffClip, deathClip, winClip;
    public bool hasPlayed = false;
    public GameObject GameOverUi, winUi;
   public GameObject CoinManag;
     public static int coinScore;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        coinScore = PlayerPrefs.GetInt("CoinScore", coinScore);
    }
    void OnCollisionEnter(Collision co)
    {
        if (co.gameObject.tag=="win")
        {
            if (!hasPlayed)
            {
                SoundManager.instance.PlaySoundFX(winClip, 0.5f);
                hasPlayed = true;
            }
            rb.isKinematic = true;
            winUi.SetActive(true);
           CoinManag.GetComponent<CoinManager>().AddScore(30);
            PlayerPrefs.GetInt("CoinScore", coinScore);
        }
    }
}

it back on, the coin thing resets to 0 . Can someone pls help me!?

This smells like you maybe are either creating a fresh coinmanager that has the value zero, or perhaps you have multiple ones going at once.

One way to prove this is to put a Debug.Log() statement into the Start() function of the coin manager and see how often and when it gets created.

A better pattern might be to make your coin manager a singleton. Here are some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data): (You probably want this variety)

Unity3D Singleton with Prefab used for predefined data: (or you could use this one if you want to put the UI canvas structure into its prefab)

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

You also do NOT drag references to the class in. You just use it wherever you want via .Instance.