Unity3D C# - NullReferenceException although Text is attached and methods work

61 views Asked by At

have no idea what is going wrong. There is a problem by outsourcing some code in another class. If the following code is in the same class, it works fine.

SearchClient.cs

void callExposeAPi (string id)
{
    ExposeClient exposeClient = (new GameObject("ExposeClient")).AddComponent<ExposeClient>();
    exposeClient.loadExpose(id);
}

ExposeClient.cs

public Text _baserentText; // is attached to Text in Unity

public void loadExpose(string id)
{
    [some API stuff...]
    Debug.Log(result.exposeexpose.realEstate.baseRent); // 480
    makeUseOfExposeUI(result.exposeexpose.realEstate);
}

void makeUseOfExposeUI (Realestate realestate)
{
    Debug.Log(realestate.baseRent); // 480
    _baserentText.text = realestate.baseRent.ToString();
}
1

There are 1 answers

2
Dilmer On BEST ANSWER

I see what is happening, in your callExposeAPi method you are creating a new instance of ExposeClient and then by looking at your comments in ExposeClient.cs you mentioned "is attached to Text in Unity" well when you assigned variables through the editor the association of _baserentText occurs with the object you manually associated through the editor, if you dynamically create an instance this association would have to be done in a different way or you could do something like this:

void callExposeAPi (string id)
{
    ExposeClient exposeClient = GameObject.Find("ExposeClient").GetComponent<ExposeClient>();
    exposeClient.loadExpose(id);
}

The difference here is that you are using a game object which already contains an ExposeClient script attached and its serialized field "_baserentText" has already been defined which will not throw a null exception.