【问题标题】:Unity3D C# - NullReferenceException although Text is attached and methods workUnity3D C# - NullReferenceException 尽管附加了文本并且方法有效
【发布时间】:2016-12-22 21:37:00
【问题描述】:

不知道出了什么问题。将一些代码外包到另一个类中会出现问题。如果以下代码在同一个类中,则可以正常工作。

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

【问题讨论】:

    标签: c# unity3d gameobject


    【解决方案1】:

    我知道发生了什么,在您的 callExposeAPi 方法中,您正在创建 ExposeClient 的新实例,然后通过查看 ExposeClient.cs 中的 cmets,当您通过编辑器分配变量时,您提到“已附加到 Unity 中的文本” _baserentText 的关联与您通过编辑器手动关联的对象发生,如果您动态创建一个实例,则必须以不同的方式完成此关联,或者您可以执行以下操作:

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

    这里的区别在于您使用的游戏对象已经包含附加的 ExposeClient 脚本,并且它的序列化字段“_baserentText”已经定义,不会引发空异常。

    【讨论】:

    • 错误依旧。 Unity Hierarchy 中不再有 ExposeClient as GameObject
    • ExposeClient.cs 已附加到 EventSystem。我使用了`ExposeClient exposeClient = GameObject.Find("EventSystem").GetComponent();`,它可以工作:)
    猜你喜欢
    • 1970-01-01
    • 2018-09-11
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多