鼠标悬停(点击)出现文本提示框

下面的是鼠标点击出现文字,如果想要鼠标移动上去出现,移出消失的话,UI可以使用OnPointerEnter跟OnPointerExit方法,命名空间是UnityEngine.EventSystems,如果是3D物体的话可以用OnMouseEnter跟OnMouseExit方法,这个是需要物体要有BoxCollider并且脚本是要挂载在物体上的.

关于GUIStyle的样式的话,可以看这篇文章.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

class ShowTextBase : MonoBehaviour
{
    public Camera curCamera;
    public Font font;
    public int fontSize = 10;
    [Multiline]//允许多行输入
    public string text = "显示的文本";
    [System.Serializable]
    public struct StructData
    {
        public string key;
        public string value;
    }

    public StructData[] datas;

    public Dictionary<string, string> texts;

    private bool showText = false;
    private GUIStyle style;

    public void Start()
    {
        texts = new Dictionary<string, string>();
        style = new GUIStyle("box");
        foreach (var v in datas)
        {
            texts.Add(v.key, v.value);
        }
    }
    //参数hit 为out类型,可得到碰撞检测的返回值;
    RaycastHit hit;
    //参数ray 为射线碰撞检测的光线(返回一个从相机到屏幕鼠标位置的光线)
    Ray ray;
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //参数ray 为射线碰撞检测的光线(返回一个从相机到屏幕鼠标位置的光线)
            ray = curCamera.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit)) //如果碰撞检测到物体
            {
                Debug.Log(hit.collider.gameObject.name);//打印鼠标点击到的物体名称
                if (texts.ContainsKey(hit.collider.gameObject.name))
                {
                    text = texts[hit.collider.gameObject.name];
                    showText = true;
                }
            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            showText = false;
        }
    }

    public void OnGUI()
    {
        style.font = font;
        style.fontSize = fontSize;
        var vt = style.CalcSize(new GUIContent(text));
        if (showText)
            GUI.Box(new Rect(Input.mousePosition.x, Screen.height - Input.mousePosition.y - vt.y, vt.x, vt.y), text, style);
    }
    // 如果是UI的话,可以用这个, 物体的话可以考虑用OnMouseEnter方法
    //public void OnPointerEnter(PointerEventData eventData)
    //{
    //    showText = true;
    //}
    //public void OnPointerExit(PointerEventData eventData)
    //{
    //    showText = false;
    //}
    
}

猜你喜欢

转载自blog.csdn.net/Marccco/article/details/126868667