NullReferenceException when try to access a variable in another script

Hey fellows.

This is the first time that I do a post here. So first of all a big Hello to everybody!

I read a couple of posts abot the NullReference issue, but didn’t found a solution for me (or didn’t understood :wink: )

I have 2 simple scripts:

  1. PlayerController.cs
  2. UI_Info.cs

In my PlayerController I’m moving around a Cube and I increment a Counter variable “BlocksCnt” when I create new Cubes (when the user press “B”). This part works fine:

Declaration of the variable:

public class PlayerController : MonoBehaviour {

    private bool Kdown;  
    public GameObject Blocks;
    public int BlocksCnt;

and using it: the counter works fine when I’m looking to the inspector.

void BuildBlocks()
    {
        if (Input.GetKeyDown("b"))
        {
            if (!Kdown)
            {
                Instantiate(Blocks);
                BlocksCnt += 1;

            }

Now the problem:
When I try to display the BlocksCnt Variable in a UI Textfield I get the NullRefExept. Error

Declaration:

public class UI_Info : MonoBehaviour {


    public GameObject myTextObj;
    private int Zahl;
    private bool MakeActive=false;
    public string Debuger;

    PlayerController plyCntrl;

I try to show the variable via the GetComponent Function (for debug purposes I’ll do it when I push the “l” Button… And I tried to store it in a String variable “Debuger” just to make sure the problem is not that I’m using the GetComponent stuff not correct. Unfortunately both versions won’t work.

void Update()
    {
        if (Input.GetKeyDown("l"))
            MakeActive = true;


        //OurComponent.text = plyCntrl.BlocksCnt.ToString();
        if (MakeActive)
             myTextObj.GetComponent<Text>().text = plyCntrl.BlocksCnt.ToString();

            Debuger = plyCntrl.BlocksCnt.ToString();
           
       
    }

I hope you have some ideas for me.

Thanks,
CodeB

Do you ever set plyCntrl to anything? If not, it’s still null when you try to get .BlocksCnt, and that’s what causes the problem.

I just used plyCntrl to access the variable in the other script. What else shall I do with it?

You have to assign it, which is to say you need to get a reference to the other component. plyCntrl = GetComponent() will do it if they are both on the same object.

1 Like

Thanks a lot. It works fine now!