Why Null Reference Exception here?

I’ve looked at quite a few script examples here in “Answers” and it looks like I’m doing things correctly but I get a “Null Reference Exception” on line 26.

Background. When I run my program, the “Start” here will print the correctly so I have the UI correctly added to the public Text object. When I run my program, I access this from another script and the function ShowDataCity() is properly accessed (?) because the Debug Log correctly prints “City Data !!!”. BUT, then I get an error on the very next line. It seems as though since it works fine in the Start function it should also work in the ShowDataCity() function. Hmmmm.

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

public class DisplayUIInfo : MonoBehaviour
    public Text testInfoData;

    private string tempText;

    private void Start()
        testInfoData.text = "Start !!!";

    public void ShowDataSingleUnit()
        Debug.Log("Single Unit Data !!!");

    public void ShowDataCity()
        string stuff = "City Data !!!";
        testInfoData.text = stuff;  ///<<<< Null Reference Exception

    public void ShowDataRawMats()
        Debug.Log("Raw Material Data !!!");

I figured out a “Work Around” for this problem. I’ve been trying to call a function on one script from another script but I kept getting a NullReferenceException and I couldn’t understand why.

...declared on ScriptB...
public ScriptA callFunctionFromA;
...called from ScriptB...
callFunctionFromA FunctionName();

The above had always worked for me in the past but in this case I was getting the NullReferenceException and I’m not sure what I was doing to cause it. In any event I changed how I accessed the other script and it now works as designed.

...declared on ScriptB…
private ScriptA _scriptA;
...added to "Start" in ScriptB…
_scriptA = FindObjectOfType<ScriptA>();
...called from ScriptB…

Both are fairly standard methods of accessing another script but I normally use the first because it apparently uses less time to work. I’ve never had a problem with the first method until this last program and again, I’m not sure what I was doing that caused the problem this time around. But using the second method works fine here and I will go ahead and use it for now and try to figure out the specific problem as I gain more knowledge about debugging, etc.

Clearly testInfoData is being destroyed or sth. at some point. You better track its activity in update

Something is destroying the testInfoData Text Object OR, something is breaking the reference to it.

You should replace this line :

public Text testInfoData;

[SerializeField] Text testInfoData;

It will prevent other scripts to break the reference.

Had the same issue. Fixed it by checking if it’s not null.

if(testInfoData != null) testInfoData.txt = stuff;

it was answered in another thread about NullReferenceException.