Unity工具
大家好,我是&心疼你的一切,不定时更新Unity开发技巧,觉得有用记得一键三连哦。
本篇文章实现一个鼠标悬浮在ui或者物体上显示文字的功能
unity鼠标悬浮ui显示文字
鼠标进入UI执行的
鼠标离开UI执行的
鼠标在ui里滑动执行的
1.
2.
搭建比较简单,各位顺便搭建吧。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class UIInputText : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerMoveHandler { public void OnPointerEnter(PointerEventData eventData) { UIController.instance_.uitextobj.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y + 25, 0); UIController.instance_.uitextobj.gameObject.SetActive(true); UIController.instance_.text.text = this.name; } //鼠标离开 public void OnPointerExit(PointerEventData eventData) { UIController.instance_.uitextobj.gameObject.SetActive(false); } //鼠标在ui里滑动 public void OnPointerMove(PointerEventData eventData) { UIController.instance_.uitextobj.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y + 25, 0); UIController.instance_.uitextobj.gameObject.SetActive(true); UIController.instance_.text.text = this.name; } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIController : MonoBehaviour { public static UIController instance_; public Transform uitextobj; public Text text; private void Awake() { instance_ = this; } }
也是同样的三个方法切记物体要有碰撞体
鼠标进入碰撞盒执行
鼠标离开碰撞盒
鼠标在碰撞盒里每帧都调用
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OBJInputText : MonoBehaviour { private void OnMouseEnter() { UIController.instance_.uitextobj.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y + 25, 0); UIController.instance_.uitextobj.gameObject.SetActive(true); UIController.instance_.text.text = this.name; } private void OnMouseExit() { UIController.instance_.uitextobj.gameObject.SetActive(false); } private void OnMouseOver() { UIController.instance_.uitextobj.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y + 25, 0); UIController.instance_.uitextobj.gameObject.SetActive(true); UIController.instance_.text.text = this.name; } }
代码比较简单,可以拓展的地方很多,还可以使用更美观的UI。
1.上述在模型上添加的鼠标显示UI的方法,在webgl打包出来之后不起作用(我是加载的ab包,代码在ab包里,所以就报错了),报错说是代码被剥离了,
默认是勾选的,我们取消勾选,重新打包即可
你的点赞就是对博主的支持,有问题记得留言
不定时更新Unity开发技巧,觉得有用记得一键三连哦。