Keep variable other script [Solved]

Hi , my “GameManager” script has “_coin” and i call this variable into “MainMenuManager” but i receive an error.

"NullReferenceException: Object reference not set to an instance of an object
CharacterSelect.Start () (at Assets/Scripts/CharacterSelect.cs:44)"

I searched other post with NullReferenceException but i cant fix my error.

Could you help me ?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CharacterSelect : MonoBehaviour {
    public static CharacterSelect instance = null;

    [Header ("Characters")]

    public bool isChaos=false;
    public bool isLumberjack=false;
    public bool isPirate=false;
    public bool isRopeMan = false;
    public bool isMiner=false;
    public bool isFisher = false;
    public bool isNTP = true;

    [Header("Buttons")]
    public Button btnStart;
    public Button btnChaos;
    public Button btnLumberjack;
    public Button btnPirate;
    public Button btnRopeMan;
    public Button btnMiner;
    public Button btnFisher;

    GameManager _gm;


    void Awake(){
        if (instance == null)
            instance = this;
        else if (instance != this) {
            Destroy (gameObject);
        }
    //    DontDestroyOnLoad (gameObject);

        DontDestroyOnLoad (_gm);
    }


    void Start () {
     
        Debug.LogWarning (_gm._coin);

        CharacterSelectable ();


        btnStart.onClick.AddListener (StartGame);
        btnChaos.onClick.AddListener (SelectChaos);
        btnLumberjack.onClick.AddListener (SelectLumberjack);
        btnPirate.onClick.AddListener (SelectPirate);
        btnRopeMan.onClick.AddListener (SelectRopeMan);
        btnMiner.onClick.AddListener (SelectMiner);
        btnFisher.onClick.AddListener (SelectFisher);

    }

    public void StartGame(){

        Application.LoadLevel ("Demo");
    }

    public void CharacterSelectable(){
            if (_gm != null) {
                _gm = GetComponent<GameManager> ();
                if (_gm._coin == 1) {
     
                    Debug.LogWarning ("Coin ==2");
                    btnChaos.interactable = true;
                }
            }

    }
    public void SelectLumberjack(){

        isLumberjack = true;
        isChaos = false;
        isPirate = false;
        isRopeMan = false;
        isMiner = false;
        isFisher = false;
        isNTP = false;
    }
    public void SelectChaos(){
     
        isChaos = true;
        isLumberjack = false;
        isPirate = false;
        isRopeMan = false;
        isMiner = false;
        isFisher = false;
        isNTP = false;
    }

    public void SelectPirate(){
     
        isPirate = true;
        isLumberjack = false;
        isChaos = false;
        isRopeMan = false;
        isMiner = false;
        isFisher = false;
        isNTP = false;
    }
 
}
public class GameManager : MonoBehaviour {
    public static GameManager instance = null;


    //CharacterSelect
    CharacterSelect _cS;
    GUIManager _guim;
    MainMenuManager _mmm;
    [Header("Characters OBJ")]

    public GameObject chaosOBJ;
    public GameObject lumberjackOBJ;
    public GameObject pirateOBJ;
    public GameObject ropeManOBJ;
    public GameObject minerOBJ;
    public GameObject fisherOBJ;
    public GameObject ntbOBJ;

    [Header ("in-Game Variables")]
    public bool isPause = false;

    public int _coin;
    public int _ruby;
    public float _timer=0.0f;

    void Awake(){
        if (instance == null)
            instance = this;
        else if (instance != this) {
            Destroy (gameObject);
        }

        DontDestroyOnLoad (gameObject);
    //    DontDestroyOnLoad (_coin);

        _cS = FindObjectOfType<CharacterSelect> ();
        _guim = FindObjectOfType<GUIManager> ();
        _mmm = FindObjectOfType<MainMenuManager> ();
    }
    void Start () {

        WhichCharacter ();

    }
   
    // Update is called once per frame
    void Update () {
        AddTimer ();
    }
       

    public void MainMenuLoad(){
        _coin = 0;
        _timer = 0;
        _guim.UpdateCoin (_coin);
        _guim.UpdateRuby (_ruby);
        _guim.UpdateTimer (_timer);
        _guim.MainMenuLoad ();
   
    }

    public void GameLevelLoad(){

        _guim.GameLevelLoad ();
    }

    public void AddCoin(){
   
        if (_cS.isPirate) {
            _coin += 2;
        }else _coin +=1;

        _guim.UpdateCoin (_coin);
    }
    public void AddTimer(){
   
        _timer += Time.deltaTime;
        _guim.UpdateTimer (_timer);
    }
       
    public void AddRuby(){
   
        _ruby += 1;
        _guim.UpdateRuby (_ruby);
   
    }

    public void Lose(){
       
        _guim.GameOver ();

        if (_coin > PlayerPrefs.GetInt ("HighScore")) {

            PlayerPrefs.SetInt ("HighScore", _coin);
        }

        if (_ruby > PlayerPrefs.GetInt ("HighRuby")) {
       
            PlayerPrefs.SetInt ("HighRuby", _ruby);
        }
        if (_timer > PlayerPrefs.GetFloat ("HighTimer")) {
            PlayerPrefs.SetFloat ("HighTimer", _timer);
        }
    }

Color tags doesn’t work inside of code tags!

Your mainMenuManager expects the GameManager to be attached to the same GameObject. Is it?

I’m also confused why you’re creating a singleton of your gamemanager, but then accessing the _coin variable through an instance of it in mainMenuManager.

I dont use MainMenuManager script,i created this script for trying.I need unlcok system with coin.

i reupload my scripts.Could you check those?

yes

Once again, you’re making a singleton of your GameManager and not accessing that singleton, but trying to create an instance of GameManager in your CharacterSelect script. This defeats the purpose of the singleton. Not only that, you aren’t even finding the GameManager and assigning it to the variable. Plus, you’re doing dontDestroyOnLoad on the instance of GameManager in your CharacterSelect script…

You should remove dontdestroyonload(_gm); from your CharacterSelect script.

Then when you want to get the coins, you should be using your singleton.

Debug.LogWarning (GameManager.instance._coin);
int coins = GameManager.instance._coin;

thank you , i trying

Hi , again.i used " int coins = GameManager.instance._coin;" but i get same error then i used

public GameManager coin=new GameManager();
Debug.LogWarning (coin._coin);

my output ;
0
UnityEngine.Debug:LogWarning(Object)
CharacterSelect:Start() (at Assets/Scripts/CharacterSelect.cs:48)

Everyone missed the important issue of the CharacterSelect script. You were calling _gm before it was assigned.
Also, your CharacterSelectable method is a bit strange.

if (_gm != null) {
_gm = GetComponent<GameManager> ()

If the reference is not null, find component.
Try this:

void Start () {
CharacterSelectable ();
Debug.LogWarning (_gm._coin);
public void CharacterSelectable(){
  if (_gm == null) {
  _gm = GetComponent<GameManager> ();
  }
  if (_gm._coin == 1) {
    Debug.LogWarning ("Coin ==2");
    btnChaos.interactable = true;
  }
}

No, everyone didn’t miss it. He’s making a singleton of the GameManager which means he has no reason to use GetComponent to make another instance of it.

If you are getting a null error when trying to access your singleton, it means it’s not initialized. You need to make sure GameManager is in the scene and is initiliazed before you try to access it. If you have GameManager and CharacterSelect in the same scene, that’s fine as long as you don’t access your GameManager singleton in Awake from your CharacterSelect script (or you have to set the load order).

Singleton or not, a missing reference is a missing reference. The script was calling the reference before the reference was set, regardless of how the reference was being set.

Also, why are you using LogWarning? Why not just Debug.Log?

Debug.LogWarning ("Coin ==2");

Lastly, I thought that it was proper form to use a static method to return the singleton?

GameManager Instance()
{
return instance;
}

And you’d call that in other scripts,

GameManager.Instance().someVariable = stuff

Is that not necessary?

Why not make coins static and be done with it?

1 Like

i used static coin

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public sealed  class GameManager : MonoBehaviour {

    public static GameManager instance = null;

    public  GameManager Instance{

        get { return instance;
        }
    }

    //CharacterSelect
    CharacterSelect _cS;
    GUIManager _guim;
    [Header("Characters OBJ")]

    public GameObject chaosOBJ;
    public GameObject lumberjackOBJ;
    public GameObject pirateOBJ;
    public GameObject ropeManOBJ;
    public GameObject minerOBJ;
    public GameObject fisherOBJ;
    public GameObject ntbOBJ;

    [Header ("in-Game Variables")]
    public bool isPause = false;
    public static int _coin;
    public int _ruby;
    public float _timer=0.0f;

    void Awake(){
       
        if (instance == null)
            instance = this;
        else   {
            Destroy (this.gameObject);
        }

        DontDestroyOnLoad (gameObject);


        _cS = FindObjectOfType<CharacterSelect> ();
        _guim = FindObjectOfType<GUIManager> ();
    }
       
    void Start () {

        WhichCharacter ();

    }
   
    // Update is called once per frame
    void Update () {
        AddTimer ();
    }
       

    public void MainMenuLoad(){
        _coin = 0;
        _timer = 0;
        _guim.UpdateCoin (_coin);
        _guim.UpdateRuby (_ruby);
        _guim.UpdateTimer (_timer);
        _guim.MainMenuLoad ();
   
    }

    public void GameLevelLoad(){

        _guim.GameLevelLoad ();
    }

    public void AddCoin(){
   
        if (_cS.isPirate) {
        _coin += 2;
        }else _coin +=1;


        _guim.UpdateCoin (_coin);   // <----- 
    }
    public void AddTimer(){
   
        _timer += Time.deltaTime;
        _guim.UpdateTimer (_timer);
    }
       
    public void AddRuby(){
   
        _ruby += 1;
        _guim.UpdateRuby (_ruby);
   
    }

    public void Lose(){
       
        _guim.GameOver ();

        if (_coin > PlayerPrefs.GetInt ("HighScore")) {

        PlayerPrefs.SetInt ("HighScore", _coin);
        PlayerPrefs.Save ();
        }

        if (_ruby > PlayerPrefs.GetInt ("HighRuby")) {
       
            PlayerPrefs.SetInt ("HighRuby", _ruby);
        }
        if (_timer > PlayerPrefs.GetFloat ("HighTimer")) {
            PlayerPrefs.SetFloat ("HighTimer", _timer);

        }
    }


    public void Options(){
        if (!isPause) {
            Time.timeScale = 0.0f;
            isPause = !isPause;
            _guim.OptionsMenuLoad ();
            //play music
        } else if (isPause)
            Time.timeScale = 1.0f;
            isPause = !isPause;
   
    }

    public void ResumeGame(){
   
        Time.timeScale = 1.0f;
        _guim.GameLevelLoad ();

    }
    public void PlayGame(){
   

    }

    public void QuitGame(){
   
        Application.Quit ();
    }



    //CHARACTERS

    public void WhichCharacter(){
       
        if (_cS.isChaos) {

            Debug.LogWarning ("Chaos  Selected");

            chaosOBJ.SetActive (true);
            lumberjackOBJ.SetActive (false);
            ropeManOBJ.SetActive (false);
            pirateOBJ.SetActive (false);

        } else if (_cS.isLumberjack) {

            Debug.LogWarning ("Lumberjack Selected");
            chaosOBJ.SetActive (false);
            lumberjackOBJ.SetActive (true);
            pirateOBJ.SetActive (false);
            ropeManOBJ.SetActive (false);

        } else if (_cS.isPirate) {
       
            Debug.LogWarning ("Pirate Selected");
            pirateOBJ.SetActive (true);
            chaosOBJ.SetActive (false);
            lumberjackOBJ.SetActive (false);
            ropeManOBJ.SetActive (false);
       
        } else if (_cS.isRopeMan) {

            Debug.LogWarning ("RopeMan Selected");
            ropeManOBJ.SetActive (true);
            pirateOBJ.SetActive (false);
            chaosOBJ.SetActive (false);
            lumberjackOBJ.SetActive (false);
       
        } else if (_cS.isMiner) {
            Debug.LogWarning ("Miner Selected");
            minerOBJ.SetActive (true);
            ropeManOBJ.SetActive (false);
            pirateOBJ.SetActive (false);
            chaosOBJ.SetActive (false);
            lumberjackOBJ.SetActive (false);
       
        } else if (_cS.isFisher) {
            Debug.LogWarning ("Fisher Selected");
            fisherOBJ.SetActive (true);
            minerOBJ.SetActive (false);
            ropeManOBJ.SetActive (false);
            pirateOBJ.SetActive (false);
            chaosOBJ.SetActive (false);
            lumberjackOBJ.SetActive (false);
       
        } else if (_cS.isNTP) {
            Debug.LogWarning ("NTP Selected");
            ntbOBJ.SetActive (true);
            fisherOBJ.SetActive (false);
            minerOBJ.SetActive (false);
            ropeManOBJ.SetActive (false);
            pirateOBJ.SetActive (false);
            chaosOBJ.SetActive (false);
            lumberjackOBJ.SetActive (false);
       
        }
    }



}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CharacterSelect : MonoBehaviour {

    public static CharacterSelect instance=null ;

    [Header ("Characters")]

    public bool isChaos=false;
    public bool isLumberjack=false;
    public bool isPirate=false;
    public bool isRopeMan = false;
    public bool isMiner=false;
    public bool isFisher = false;
    public bool isNTP = true;

    [Header("Buttons")]
    public Button btnStart;
    public Button btnChaos;
    public Button btnLumberjack;
    public Button btnPirate;
    public Button btnRopeMan;
    public Button btnMiner;
    public Button btnFisher;


    //public static coin = GameManager.instance._coin;
    //int    coin =new GameObject.FindGameObjectWithTag ("CharacterSelect").GetComponent<GameManager> () as GameManager;

    //public GameManager coin=new GameManager();
//    public GameManager coin;
    //GameManager _gm =new GameManager();

//    int _coin = GameManager.instance._coin;

    void Awake(){
       

        if (instance == null)
            instance = this;
        else if (instance != this) {
            Destroy (gameObject);
        }
        DontDestroyOnLoad (gameObject);


    }


    void Start () {

        CharacterSelectable ();
        btnStart.onClick.AddListener (StartGame);
        btnChaos.onClick.AddListener (SelectChaos);
        btnLumberjack.onClick.AddListener (SelectLumberjack);
        btnPirate.onClick.AddListener (SelectPirate);
        btnRopeMan.onClick.AddListener (SelectRopeMan);
        btnMiner.onClick.AddListener (SelectMiner);
        btnFisher.onClick.AddListener (SelectFisher);

    }

    public void Update(){

    }
    public void StartGame(){
        Application.LoadLevel ("Demo");
    }

    public void CharacterSelectable( ){
       
           
        Debug.Log (GameManager._coin);
    }
    public void SelectLumberjack(){

        isLumberjack = true;
        isChaos = false;
        isPirate = false;
        isRopeMan = false;
        isMiner = false;
        isFisher = false;
        isNTP = false;
    }
    public void SelectChaos(){
       
        isChaos = true;
        isLumberjack = false;
        isPirate = false;
        isRopeMan = false;
        isMiner = false;
        isFisher = false;
        isNTP = false;
    }

    public void SelectPirate(){
       
        isPirate = true;
        isLumberjack = false;
        isChaos = false;
        isRopeMan = false;
        isMiner = false;
        isFisher = false;
        isNTP = false;
    }
    public void SelectRopeMan(){
       
        isRopeMan = true;
        isPirate = false;
        isLumberjack = false;
        isChaos = false;
        isMiner = false;
        isFisher = false;
        isNTP = false;
    }

    public void SelectMiner(){

        isMiner = true;
        isChaos = false;
        isPirate = false;
        isLumberjack = false;
        isRopeMan = false;
        isFisher = false;
        isNTP = false;
    }
    public void SelectFisher(){
        isFisher = true;
        isMiner = false;
        isChaos = false;
        isPirate = false;
        isLumberjack = false;
        isRopeMan = false;
        isNTP = false;
    }
}

and my other class Player;

using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {


    CharacterSelect _cS;
    GameManager _gm;

    [Header("Variables")]
    public float fRunMin;
    public float fRunMax;
    public float fJumpForce;
    private Rigidbody rb;
    private float JumpCount=0;
    private float speed = 5.0f;

    private float curScale=0.5f;
    public float startScale=0.5f;
     float shrinkSpeed=0.1f;

    public GameObject coin;
    public GameObject ruby;

..
..
..
..
..
    _cS = FindObjectOfType<CharacterSelect> ();

            if (col.gameObject.tag == "SwordFishes") {
                curScale = Mathf.MoveTowards (curScale, startScale, Time.deltaTime * 0.01f);
                _swordFish.gameObject.transform.localScale = new Vector3 (curScale, curScale, curScale);
                Destroy (col.collider);
                Destroy(col.gameObject, 0.1f);

                _gm.AddCoin ();
            }
....
...

value still “0”

Unsure now. Static should make sure theres only one instance of that int.
Sure you’re not resetting it somewhere?

I fixed my problem.Thank all the answer