首页 > 代码库 > 【Unity3D自学记录】Unity3D显示NPC名称

【Unity3D自学记录】Unity3D显示NPC名称

using UnityEngine;
using System.Collections;

public class NPCName : MonoBehaviour {
    //主角对象
    private GameObject player;
    //主摄像机对象
    private Camera camera;
    //NPC名称
    private string name = "我是NPC";

    void Start()
    {
        //根据Tag得到主角对象
        player = GameObject.FindGameObjectWithTag("MainCamera");
        camera = Camera.main;
    }

    void OnGUI()
    {
        //得到NPC头顶在3D世界中的坐标
        Vector3 worldPosition = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
        //根据NPC头顶的3D坐标换算成它在2D屏幕中的坐标
        Vector2 position = camera.WorldToScreenPoint(worldPosition);
        //得到真实NPC头顶的2D坐标
        position = new Vector2(position.x, Screen.height - position.y);
        //计算NPC名称的宽高
        Vector2 nameSize = GUI.skin.label.CalcSize(new GUIContent(name));
        //设置显示颜色为黄色
        GUI.color = Color.red;
        //绘制NPC名称
        GUI.Label(new Rect(position.x - (nameSize.x / 2), position.y - nameSize.y, nameSize.x, nameSize.y), name);

    }
}