0

I am new to game dev and this is my first time to develop a game. Here I am trying to print the total score in all game collected by the player. Like if the player played for 10 times then the score 1 to 10 is added to the total coin. In this code, I want to show it to the UI.

enter image description here

Here is the error that I recieved: NullReferenceException: Object reference not set to an instance of an object MainManager.Start () (at Assets/Scripts/Main/MainManager.cs:28)

As you can see here in my code, this line highscore.text = "" + PlayerPrefs.GetInt("bestScore"); has no error. But in this line totalcoin.text = "" + PlayerPrefs.GetInt("totalCoin"); the error of object reference persist.

Here is the full code:

using System.Net.Mime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class MainManager : MonoBehaviour {

    public static MainManager instance;

    public Text highscore;
    public Text totalcoin;

    GameCounter counter;


    void Awake() {
        Time.timeScale = 1f;

        if (instance == null) {
            instance = this;
        }
    }

    void Start () {
        highscore.text = "" + PlayerPrefs.GetInt("bestScore");// This already show the best score for every game
        totalcoin.text = "" + PlayerPrefs.GetInt("totalCoin"); // Here is the error pointing . Not showing the total coin for all the games the player played
         if ((counter == null) && (GetComponent<GameCounter>() != null))
         {
             counter = GetComponent<GameCounter>();
         }
         else
         {
             Debug.LogWarning("...");
         }
    }
    
    void Update () {
        
    }

    public void PlayGame() {
        counter.PlayGameLimit();
    }

    public void QuitGame() {
        Application.Quit();
    }
}
Gheh
  • 35
  • 7
  • 1
    `totalcoin` must be null, in which case `totalcoin.text` will throw a null reference exception. – dbc Dec 25 '21 at 15:31

0 Answers0