简体   繁体   中英

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

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM