3DText - 通过脚本更改文本 - Unity

时间:2013-10-22 09:41:40

标签: unity3d

我已经阅读了很多关于如何从脚本中更改3DText文本的问题。

很多人建议如下:::

GetComponent(TextMesh).text = "blah";

但是当我尝试使用此功能时,我收到错误Expression denotes a类型',其中variable',值'或method group' was expected

我尝试了很多例子并且无法让它真正起作用。

TextMesh textMesh;
textMesh = (TextMesh) descriptionObject.transform.GetComponent("Text Mesh");
textMesh.text = "Name : ABC";

上面的代码虽然编译没有错误但不会改变文本。有人可以帮我解决这个问题吗?如何更改3DText对象的TEXT。

...谢谢

2 个答案:

答案 0 :(得分:3)

这将是一个比已经给出的更漂亮的解决方案(示例中使用的C#脚本):

//define a Textmesh that we want to edit 
public TextMesh tm;

// here in start method (run at instantiating of script) i find component of type
    // TextMesh ( <TextMesh> ) of object named"nameOfTheObject" and reference it
    // via tm variable;
void Start () {
    tm = (TextMesh)GameObject.Find ("nameOfTheObject").GetComponent<TextMesh>();
           // here we change the value of displayed text
            tm.text = "new Text u want to see";
}

或者如果你想以尽可能最短的方式(语法方式):

//keep in mind this requires for the script to be attached to the object u
// are editing (the 3dText);
//same as above, the only difference is the note in the line above as this
// method is run from gameObject.GetComponent....
// gameObject is a variable which would be equivalent of this.GetComp...
// in some other programming languages 

GetComponent<TextMesh>().text ="new Text u want";

答案 1 :(得分:1)

这是作品!!!!

textMesh = (TextMesh) descriptionObject.transform.GetComponent(typeof(TextMesh));
        textMesh.text = "Name : ABC";