当前位置:   article > 正文

unity 鼠标放置在3D物体上,显示物体名称_unity 展示物体名字

unity 展示物体名字

做个记录,也方便自己以后查看,大家共同交流

 源代码

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TestShow : MonoBehaviour
  6. {
  7. //要显示的ui
  8. public RectTransform tip;
  9. // Update is called once per frame
  10. void Update()
  11. {
  12. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  13. RaycastHit hit;
  14. bool raycast = Physics.Raycast(ray, out hit);
  15. if (raycast)
  16. {
  17. GameObject go = hit.collider.gameObject;
  18. tip.gameObject.SetActive(true);
  19. tip.GetComponentInChildren<Text>().text = go.GetComponent<ObjectTips>().ObjectName;
  20. FollowMouse(hit .point);
  21. }
  22. else
  23. {
  24. tip.gameObject.SetActive(false);
  25. }
  26. }
  27. //ui位置实时变化
  28. void FollowMouse(Vector3 position)
  29. {
  30. Vector3 screenPoint = Camera.main.WorldToScreenPoint(position);
  31. tip.anchoredPosition = screenPoint +new Vector3(10f, 5f, 0);
  32. }
  33. }

挂载在任意物体上,记得把tip赋值,在3D物体上加collider组件,射线才会检测到物体

  1. using UnityEngine;
  2. public class ObjectTips : MonoBehaviour
  3. {
  4. //物体显示名称
  5. //挂在物体上
  6. public string ObjectName;
  7. }

DEMO地址

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号