jad*_*ns4 6 text unity-game-engine
我正在开发一个从网站导入文本数据的C#类.这很好用.我丢失的地方是如何在字符串变量中包含所有文本后在Unity 4.6中显示文本.任何建议表示赞赏.
Unity 4.6 UI系统具有名为的组件Text
。您可以在此处观看视频教程。我也建议您检查一下它的API。
与往常一样,您有两个选择关于如何将此组件添加到游戏对象中。您可以从编辑器中进行操作(只需单击要在层次结构中具有此组件的游戏对象,然后添加Text
组件)。或者,您也可以使用脚本从脚本中进行操作gameObject.AddComponent<Text>()
。
如果您还不熟悉组件,建议您阅读这篇文章。
无论如何,using UnityEngine.UI;
由于Text
类位于UnityEngine.UI
名称空间中,因此您需要在脚本的最顶部添加。好的,现在回到脚本,该脚本将设置Text
component 的值。
首先,您需要引用Text
组件的变量。可以通过将其公开给编辑器来完成:
public class MyClass : MonoBehaviour {
public Text myText;
public void SetText(string text) {
myText.text = text;
}
}
Run Code Online (Sandbox Code Playgroud)
并将带有文本组件的gameObject附加到Editor中的该值。
另外一个选项:
public class MyClass : MonoBehaviour {
public void SetText(string text) {
// you can try to get this component
var myText = gameObject.GetComponent<Text>();
// but it can be null, so you might want to add it
if (myText == null) {
myText = gameObject.AddComponent<Text>();
}
myText.text = text;
}
}
Run Code Online (Sandbox Code Playgroud)
以前的脚本不是一个好例子,因为GetComponent
它实际上很昂贵。因此,您可能要缓存其参考:
public class MyClass : MonoBehaviour {
Text myText;
public void SetText(string text) {
if (myText == null) {
// looks like we need to get it or add
myText = gameObject.GetComponent<Text>();
// and again it can be null
if (myText == null) {
myText = gameObject.AddComponent<Text>();
}
}
// now we can set the value
myText.text = text;
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,“ GetComponent或Add(如果尚不存在则添加)”的模式非常常见,通常在Unity中您要定义函数
static public class MethodExtensionForMonoBehaviourTransform {
static public T GetOrAddComponent<T> (this Component child) where T: Component {
T result = child.GetComponent<T>();
if (result == null) {
result = child.gameObject.AddComponent<T>();
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以将其用作:
public class MyClass : MonoBehaviour {
Text myText;
public void SetText(string text) {
if (myText == null) {
// looks like we need to get it or add
myText = gameObject.GetOrAddComponent<Text>();
}
// now we can set the value
myText.text = text;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22551 次 |
最近记录: |