I tried to save the collected coin amount after finishing any level in unity 2D

but didn’t work, when playing same level in multiple times didn’t save collected coin amount.

Here is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CoinMain : MonoBehaviour
{
    Text coinMainText;
    public static int coinMainAmount =0;

    public static CoinMain instance; // Singleton instance

    void Awake()
    {
        // Ensure only one instance of CoinManager exists
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        UpdateStarUI();
        PlayerPrefs.SetInt("MCAw", coinMainAmount);
    }

    private void UpdateStarUI()
    {
        // Assuming you have a total number of levels stored in a variable like 'totalLevels'
        int totalLevels = 45;

        for (int i = 0; i <= totalLevels; i++)
        {
            coinMainAmount += PlayerPrefs.GetInt("MainCoinAmount" + i);
        }

        coinMainText.text = coinMainAmount.ToString("000000");
    }

}

The issue you are having appears to be in the line coinMainAmount += PlayerPrefs.GetInt("MainCoinAmount" + i);. What is happening there is that instead of adding I to the MainCoinAmount, you are instead concatenating the strings “MainCoinAmount” and i, and trying to get that number. Essentially, you are looking for a variable that does not exist, because you arew looking for “MainCoinamount0” instead of “MainCoinAmount”. To fix this, replace it with the code coinMainAmount += PlayerPrefs.GetInt("MainCoinAmount") + i; Another issue you may be having, is that(although this one may be false, as I do not know your PlayerPrefs code), the integer you are trying to retrieve, MainCoinAmount, does not appear to be the integer you are updating. The line PlayerPrefs.SetInt("MCAw", coinMainAmount); sets the MCAw variable to coinMainAmount, but then you are trying to reference a different variable named “MainCoinAmount” in a later line. However, this discrepancy may be intentional and I just do not know all of your code(although if it is, I would make sure that your function callstack is in order so you can prevent desync across scripts)