求教,怎么使用NGUI UILabel调用unity3d的内置字体

2024-11-08 00:44:26
推荐回答(1个)
回答(1):

首先我们创建一个Label一个Button,然后创建两个C#类,一个FloatingText绑定到Label上,一个FloatingTextDriver绑定到Button上,这样我们Inspector面板中把相应的参数赋值即可,当我们点击按钮的时候,Label文本出现,并且位置一直跟随Target运动。

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

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

Source code
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);

}

}

Source code
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();
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;
}

}