2013-10-18 54 views
0

我试图从作为我的文本网格对象的父级的类访问我的TextMesh的文本组件。在运行时更改文本网格的文本值

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

这是代码握着我的祖父对象上(在这种情况下,摄像机),平面是相机这仅仅是一个平面物体,被称为平面和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。虽然我得到错误,但我一定在做错事。

有人请教育我做错了什么吗?

+0

你是什么意思,当你说TextMesh被称为FloorMenu?我不相信你可以命名这样的组件。尝试将其更改为GetComponent(“TextMesh”);并看看会发生什么。 – stevepkr84

回答

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"; 
相关问题