NGUI 动态改变Label字体

来源:互联网 发布:Linux用wine玩英雄联盟 编辑:程序博客网 时间:2024/04/18 13:17

这篇文章的含金量可能并不是很高,也许几乎是一点没有,因为很多游戏中不会这么无聊的在游戏过程中还要改变字体,基本都是静态的图片或者文本就可以了。之所以写这篇文章是为了熟悉一下C#中如何定义getter与setter。首先我们创建一个Label一个Button,然后创建两个C#类,一个FloatingText绑定到Label上,一个FloatingTextDriver绑定到Button上,这样我们Inspector面板中把相应的参数赋值即可,当我们点击按钮的时候,Label文本出现,并且位置一直跟随Target运动。


Label中的Target为空,我们在FloatingTextDriver的OnClick事件中动态添加了Target对象。

下面是FloatingTextDriver与FloatingText两个类的具体实现:

using UnityEngine;using System.Collections; public class FloatingTextDriver : MonoBehaviour {     public GameObject target;    public FloatingText ft;    public UIFont font;    IEnumerator OnClick()    {        ft.Target = target;        ft.Text = "libufan";        ft.Active = true;         yield return new WaitForSeconds(2.0f);         ft.Font = font;        ft.FontSize = new Vector3(50, 50, 1);     } }

using UnityEngine;using System.Collections; public class FloatingText : MonoBehaviour { private UILabel _lbl;     public GameObject _target;    public Camera worldCamera;    public Camera guiCamera;    private Vector3 pubPos;     private bool _active; void Awake(){_lbl = GetComponent<UILabel>();if(_lbl == null){Debug.LogError("Could not fint the UILabel!");}}     void Start()    {        guiCamera = NGUITools.FindCameraForLayer(gameObject.layer);    } public Color TextColor{get {return _lbl.color;}set {_lbl.color = value;}}     public string Text    {        get { return _lbl.text; }        set { _lbl.text = value; }    }     public bool Active    {        get { return _active; }        set { _active = value; }    }     public GameObject Target    {        get { return _target; }        set {            _target = value;            worldCamera = NGUITools.FindCameraForLayer(_target.layer);        }    }     public UIFont Font    {        get { return _lbl.font; }        set { _lbl.font = value; }    }     public Vector3 FontSize    {        get { return _lbl.transform.localScale; }        set { _lbl.transform.localScale = value; }    }     void LateUpdate()    {         if (!_active)        {            return;        }         pubPos = worldCamera.WorldToViewportPoint(_target.transform.position);        pubPos = guiCamera.ViewportToWorldPoint(pubPos);        pubPos.z = 0;        transform.position = pubPos;    } }