Search code examples
c#unity-game-enginemonodevelop

A NullReferenceException using Unity.5.6.5 with a script reference


There are 3 Scripts at play in the problem I am experiencing.

Firstly I have an object which I whish to select which the following code to comunicate with the "GameManager"(the secound relavent object) that it is the selected object this works:

public void OnMouseDown ()
{
    if(TheGameManager.SelectableOn || TheGameManager.SelectedObject == this){



    //If clicked and not already selected then determain this as the selected object
    OnOff = !OnOff;
    if(FindObjectOfType<GameManager>().SelectedObject != this){OnOff = true;}
    if(FindObjectOfType<GameManager>().SelectedObject == null){OnOff = true;}

    //Determain this as the selected object
    if(OnOff){FindObjectOfType<GameManager>().SelectedObject = this; TheGameManager.UpdateZUIInterface("close");}
        else{FindObjectOfType<GameManager>().SelectedObject = null;TheGameManager.ResetAllUIToDefault();}

    TheGameManager.UpdateAllUIElements();
    }

This is how it looks in the inspector Picture of the first object being selected The problem occures however when I try to reference this instance safed within the GameManager.

[SerializeField] GameManager TheGameManager;

public void OnMouseDown (){

    Selectable SelectedObject = TheGameManager.ProvideSelectedObject();
    Debug.Log(SelectedObject.gameObject);
    Debug.Log(TheGameManager.SelectedObject.GetComponent<Selectable>().gameObject);


}

Neither of these two ways to acces the instance works. I could imagine a direct reference send from the instance itself would work however I try to use the GameManager as a central storage of most of the frequently uses variables so i would like to avoid doing that. Do any of you have any solution or thoughts? I would love to hear from you.


Solution

  • If the TheGameManager is setup as a Singleton, then it likely has a static instance property or field. In that case, you should be calling the static isntance field instead of a local instance of the TheGameManager

    So, remove: [SerializeField] GameManager TheGameManager;

    And now call the game manager like this:

    varSelectedObject = TheGameManager.instance.ProvideSelectedObject();
    

    This is supposition, but I dare say it's the cause of your problems. If this isn't the case, we'll need to see the actual code for TheGameManager.