0

I am trying to set a score for the whole game in Unity2D, but it only saves it for one scene, then it comes back to 0 for the next scene. My game has 16 scenes and I need to score to be a total score instead of one score per scene. Is there a way to save the score for the whole game?

Here is the code. I also tried using DontDestroyOnLoad but it keeps resetting the whole score. Please assist me. I also need this for my coin system, to keep the coin count, the coin code is below.

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

public class ScoreManager : MonoBehaviour
{
    public static ScoreManager instance;

    public TextMeshProUGUI scoreText;
    public TextMeshProUGUI highScoreText;

    int score = 0;
    int highscore = 0;


    private void Awake()
    {
        instance = this;
        
    }
    // Start is called before the first frame update
    void Start()
    {
        highscore = PlayerPrefs.GetInt("highscore", 0); 
        scoreText.text = "SCORE " + score.ToString();
        highScoreText.text = "HIGHSCORE: "+ highscore.ToString();
        if (highscore < score) { PlayerPrefs.SetInt("highscore", score); }
            
    }
    public void AddPoints()
    {
        
        score += 100;
        scoreText.text = "SCORE " + score.ToString();
        PlayerPrefs.SetInt("highscore", score);
       
    }
    public void AddPoints2()
    {
        score += 50;
        scoreText.text = "SCORE " + score.ToString();
        
    }





}

Coins code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class CoinPicker : MonoBehaviour
{
    private float moneda = 0;
    public AudioClip MonedaSound;
    public float monedatotal;

    public TextMeshProUGUI textMonedas;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.transform.tag== "moneda")
        {
            moneda= moneda+100;
            textMonedas.text = moneda.ToString();
            Camera.main.GetComponent<AudioSource>().PlayOneShot(MonedaSound);
            Destroy(other.gameObject);
            monedatotal = moneda;
            ScoreManager.instance.AddPoints();
        }
    }
}

enter image description here

2 Answers2

0

Use PlayerPrefs, as you use it for storing the highest score. Also, you have a strange behavior of your highest score logic. Every time, you add points, you just overwrite the highest score with a current score

JottoWorol
  • 281
  • 2
  • 9
0

You could make another APPLICATION or even SAVED(if you want to store score if app quits too) variable for the total score, and keep this logic for the levels score.

H_7
  • 287
  • 1
  • 5
  • 18