unity实现多个物体或单个物体让其单击物体让其显示再次单击让其隐藏
- IT业界
- 2025-08-19 04:30:02

unity 实现单击物体让其显示或隐藏,再次单击显示或隐藏
using System.Collections; using System.Collections.Generic; using Unity.Burst.CompilerServices; using UnityEngine; using UnityEngine.EventSystems;
public class ToggleObjects : MonoBehaviour { //private float tapThreshold = 0.25f; //private float tapTimer = 0.0f; //private bool tap = false; //private void Update() //{ // if (Input.GetMouseButtonDown(0)) // { // if (Time.time < this.tapTimer + this.tapThreshold) // { // RaycastHit hit; // Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 创建射线从相机指向鼠标点击位置 // if (Physics.Raycast(ray, out hit)) // 如果射线击中了物体 // { // GameObject clickedObject = hit.transform.gameObject; // 获取被点击的物体 // if (clickedObject == this.gameObject) // 如果是当前物体被点击 // { // Debug.Log(“双击”); // this.tap = false; // return; // } // }
// } // this.tap = true; // this.tapTimer = Time.time; // } // if (this.tap == true && Time.time > this.tapTimer + this.tapThreshold) // { // RaycastHit hit; // Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 创建射线从相机指向鼠标点击位置 // if (Physics.Raycast(ray, out hit)) // 如果射线击中了物体 // { // GameObject clickedObject = hit.transform.gameObject; // 获取被点击的物体 // if (clickedObject == this.gameObject) // 如果是当前物体被点击 // { // this.tap = false; // Debug.Log("单击"); // return; // } // } // } //} private float lastClickTime = 0f; private float doubleClickThreshold = 0.5f; private bool isVisible = true; private bool isVisible1 = true; void Start() { } void Update() { // 检测鼠标左键的点击事件 if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 创建射线从相机指向鼠标点击位置 if (Physics.Raycast(ray, out hit)) // 如果射线击中了物体 { GameObject clickedObject = hit.transform.gameObject; // 获取被点击的物体 if (clickedObject.name == "Cube") // 如果是当前物体被点击 { isVisible = !isVisible; // 切换可见性状态 //toggleRenderer(isVisible); // 根据可见性状态切换MeshRenderer的显示或隐藏 if(isVisible==true) { Debug.Log("true:Cube打开"); } else { Debug.Log("false:Cube关闭"); } } if (clickedObject.name == "Cube1") // 如果是当前物体被点击 { isVisible1 = !isVisible1; // 切换可见性状态 //toggleRenderer(isVisible); // 根据可见性状态切换MeshRenderer的显示或隐藏 if (isVisible1 == true) { Debug.Log("true:Cube1打开"); } else { Debug.Log("false:Cube1关闭"); } } } } } private void toggleRenderer(bool visible) { MeshRenderer renderer = GetComponent<MeshRenderer>(); // 获取物体的MeshRenderer组件 if (renderer != null) { renderer.enabled = visible; // 根据可见性状态设置MeshRenderer的启用或禁用 } }}
unity实现多个物体或单个物体让其单击物体让其显示再次单击让其隐藏由讯客互联IT业界栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“unity实现多个物体或单个物体让其单击物体让其显示再次单击让其隐藏”
上一篇
cpolar内网穿透