GUI Text表示在屏幕座標中顯示你導入的任何字體的文本。下圖建立一個GUI Text對象。數組
相關的屬性以下所示:dom
Text 文本:要顯示的字符串。字體
Anchor 錨:文本上的哪一個點共享此變換的位置。ui
Alignment 對齊:GUIText如何多行對齊。spa
Pixel Offset 像素偏移:文本中的相對於GUIText在屏幕上的位置的偏移。code
Line Spacing 行距:文本行之間的間距orm
Tab Size 製表符大小:多少空格將被插入一個選項卡("\t")字符。做爲一個空格字符偏移量的倍數(德語multiplum 倍數)。協程
Font 字體:顯示文本所用的字體對象
Material 材質:關於包含被繪製字符的材質。若是設置了這個屬性,會覆蓋掉原來在字體資源。blog
Pixel Correct 像素修正:若是啓用,全部文本字符將以導入的字體紋理的大小來進行繪製。若是禁用,字符將被在變換規模的基礎上進行調整
下面是一個使用GUI Text顯示遊戲分數的參考腳本:
using UnityEngine; using System.Collections; public class Score : MonoBehaviour { public int score = 0; // 玩家分數 private PlayerControl playerControl; // 玩家腳本 private int previousScore = 0; // 上一幀的分數 void Awake () { // 獲取玩家的腳本組件 playerControl = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerControl>(); } void Update () { // 設置GUI的文本 guiText.text = "Score: " + score; // 若是分數改變,使用playerControl腳本的一個協程來隨機播放一個聲音如:good,go go go等 if(previousScore != score) playerControl.StartCoroutine(playerControl.Taunt()); // 設置上一個分數 previousScore = score; } }
public IEnumerator Taunt() { // 獲取一個隨機數 float tauntChance = Random.Range(0f, 100f); // 若是大於50則播放音頻 if(tauntChance > tauntProbability) { // 等待1秒 yield return new WaitForSeconds(tauntDelay); // 檢查是否有音頻正在播放 if(!audio.isPlaying) { // 隨機取一個音頻 tauntIndex = TauntRandom(); // 播放 audio.clip = taunts[tauntIndex]; audio.Play(); } } } int TauntRandom() { // 隨機取一個音頻數組的索引 int i = Random.Range(0, taunts.Length); // 若是和上一次的同樣,則從新取隨機數 if(i == tauntIndex) return TauntRandom(); else return i; }
每一個GameObject都具備GUI Text的屬性guiText,咱們能夠直接經過該屬性來獲取GameObject的GUI Text對象或者其文本,下面是一個實現上面分數陰影的腳本。
using UnityEngine; using System.Collections; public class ScoreShadow : MonoBehaviour { public GameObject guiCopy; // A copy of the score. void Awake() { // Set the position to be slightly down and behind the other gui. Vector3 behindPos = transform.position; behindPos = new Vector3(guiCopy.transform.position.x, guiCopy.transform.position.y-0.005f, guiCopy.transform.position.z-1); transform.position = behindPos; } void Update () { // Set the text to equal the copy's text. guiText.text = guiCopy.guiText.text; } }