当前位置:   article > 正文

鼠标悬停(点击)出现文本提示框_unity点击模型弹出文本框

unity点击模型弹出文本框

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

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

  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.EventSystems;
  4. class ShowTextBase : MonoBehaviour
  5. {
  6. public Camera curCamera;
  7. public Font font;
  8. public int fontSize = 10;
  9. [Multiline]//允许多行输入
  10. public string text = "显示的文本";
  11. [System.Serializable]
  12. public struct StructData
  13. {
  14. public string key;
  15. public string value;
  16. }
  17. public StructData[] datas;
  18. public Dictionary<string, string> texts;
  19. private bool showText = false;
  20. private GUIStyle style;
  21. public void Start()
  22. {
  23. texts = new Dictionary<string, string>();
  24. style = new GUIStyle("box");
  25. foreach (var v in datas)
  26. {
  27. texts.Add(v.key, v.value);
  28. }
  29. }
  30. //参数hit 为out类型,可得到碰撞检测的返回值;
  31. RaycastHit hit;
  32. //参数ray 为射线碰撞检测的光线(返回一个从相机到屏幕鼠标位置的光线)
  33. Ray ray;
  34. private void Update()
  35. {
  36. if (Input.GetMouseButtonDown(0))
  37. {
  38. //参数ray 为射线碰撞检测的光线(返回一个从相机到屏幕鼠标位置的光线)
  39. ray = curCamera.ScreenPointToRay(Input.mousePosition);
  40. if (Physics.Raycast(ray, out hit)) //如果碰撞检测到物体
  41. {
  42. Debug.Log(hit.collider.gameObject.name);//打印鼠标点击到的物体名称
  43. if (texts.ContainsKey(hit.collider.gameObject.name))
  44. {
  45. text = texts[hit.collider.gameObject.name];
  46. showText = true;
  47. }
  48. }
  49. }
  50. if (Input.GetMouseButtonUp(0))
  51. {
  52. showText = false;
  53. }
  54. }
  55. public void OnGUI()
  56. {
  57. style.font = font;
  58. style.fontSize = fontSize;
  59. var vt = style.CalcSize(new GUIContent(text));
  60. if (showText)
  61. GUI.Box(new Rect(Input.mousePosition.x, Screen.height - Input.mousePosition.y - vt.y, vt.x, vt.y), text, style);
  62. }
  63. // 如果是UI的话,可以用这个, 物体的话可以考虑用OnMouseEnter方法
  64. //public void OnPointerEnter(PointerEventData eventData)
  65. //{
  66. // showText = true;
  67. //}
  68. //public void OnPointerExit(PointerEventData eventData)
  69. //{
  70. // showText = false;
  71. //}
  72. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/118345
推荐阅读
相关标签
  

闽ICP备14008679号