[Unity2D]GUI Text

    GUI Text表示在屏幕坐标中显示你导入的任何字体的文本。下图创建一个GUI Text对象。

相关的属性如下所示:

Text 文本:要显示的字符串。

Anchor 锚:文本上的哪个点共享此变换的位置。

Alignment 对齐:GUIText如何多行对齐。

Pixel Offset 像素偏移:文本中的相对于GUIText在屏幕上的位置的偏移。

Line Spacing 行距:文本行之间的间距

Tab Size 制表符大小:多少空格将被插入一个选项卡("\t")字符。作为一个空格字符偏移量的倍数(德语multiplum 倍数)。

Font 字体:显示文本所用的字体

Material 材质:关于包含被绘制字符的材质。如果设置了这个属性,会覆盖掉原来在字体资源。

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;
    }
}

 

posted on 2014-09-25 20:27  linzheng  阅读(2714)  评论(0编辑  收藏  举报

导航