在运行时更改textmesh的文本值

时间:2013-10-18 14:56:33

标签: c# unity3d

我正在尝试从一个类中访问TextMesh的文本组件,该类是我的文本网格对象的Grand父级。

我一直在玩这个代码,但无法改变它。我做错了什么?是否有额外的电话或我需要做的事情?

这是代码保存在我的祖父对象(在这种情况下是一个摄像机)上,平面是摄像机的直接子节点,它只是一个平面对象,称为平面,textmesh是我的平面对象的子节点。文本网格称为FloorMenu。

TextMesh text = (TextMesh)GameObject.Find("Plane").GetComponent("FloorMenu");
text.text = "test";

当我尝试运行此代码时,我收到以下错误,当双击时,将我指向text.text行:

NullReferenceException: Object reference not set to an instance of an object

据我所知,第一行应该指向处理给定错误的TextMesh。虽然我收到错误,但我一定是做错了。

有人可以教育我做错了吗?

1 个答案:

答案 0 :(得分:0)

你组装这行代码的方式阻止你看到它的哪一部分抛出了NullReferenceException。

    // Note: This is C#

    var plane = GameObject.Find("Plane");

    var floorMenu = plane.GetComponent("FloorMenu"); // <-- FYI: GetComponent("FloorMenu") seems wrong (probably null).
    // var floorMenu = plane.GetComponent(typeof(TextMesh)); // this might work, depends on how your scene is structured.

    Debug.Log("is a TextMesh?: " + (floorMenu is TextMesh)); // Bet you this is false.  

    var text = (TextMesh) floorMenu;

    text.text = "test";