赞
踩
- using UnityEngine;
- using UnityEngine.EventSystems;
-
- public class ObjectClickHandler : MonoBehaviour
- {
- public Transform player;
- public Canvas associatedCanvas;
- public float distanceThreshold = 2f;//规定触发点击事件的最大距离
-
- // 初始时Canvas状态为未激活
- void Start()
- {
- if (associatedCanvas != null)
- {
- associatedCanvas.gameObject.SetActive(false);
- }
- }
-
- //鼠标点击触发
- void OnMouseDown()
- {
- Debug.Log("Mouse Clicked on Cube");
-
- // 检查是否设置了player
- if (player != null)
- {
- //判断鼠标(默认在视角中心点)距离点击物体距离
- float distance = Vector3.Distance(transform.position, player.position);
- if (distance <= distanceThreshold)
- {
- //距离小于所规定的距离,调用TriggerCanvasEvent()方法
- TriggerCanvasEvent();
- }
- }
- else
- {
- Debug.LogError("Player not assigned to CubeClickHandler script. Please assign it in the Inspector.");
- }
- }
-
- void TriggerCanvasEvent()
- {
- // 确保关联的Canvas不为null
- if (associatedCanvas != null)
- {
- // 激活 Canvas
- associatedCanvas.gameObject.SetActive(true);
-
- // 禁用玩家控制视角
- // 这里假设你的玩家控制脚本是一个名为 "PlayerController" 的脚本
- PlayerController playerController = player.GetComponent<PlayerController>();
- if (playerController != null)
- {
- playerController.enabled = false; //禁用(或关闭)与 PlayerController 脚本关联的游戏对象的脚本组件
- }
-
- // 显示光标
- Cursor.visible = true;
- // 取消锁定光标在中心
- Cursor.lockState = CursorLockMode.None;
-
- // 触发 Canvas 事件
- EventTrigger trigger = associatedCanvas.GetComponent<EventTrigger>();
- if (trigger != null)
- {
- ExecuteEvents.Execute(associatedCanvas.gameObject, new BaseEventData(EventSystem.current), ExecuteEvents.submitHandler);
- }
- }
- }
- }
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class NewBehaviourScript : MonoBehaviour
- {
- public Canvas canvasToClose;//所需关闭的canvas
- public Transform player;
-
- void Update()
- {
- // 检测是否按下 Esc 键
- if (Input.GetKeyDown(KeyCode.Escape))
- {
- ToggleCanvas();
- }
- }
- void ToggleCanvas()
- {
- Debug.Log("ToggleCanvas method called");
- if (canvasToClose != null)
- {
- canvasToClose.gameObject.SetActive(false); // 关闭 Canvas
- Cursor.lockState = CursorLockMode.Locked;//固定鼠标在视角中心
- Cursor.visible = false;//隐藏鼠标
- if (player != null)
- {
- PlayerController playerController = player.GetComponent<PlayerController>();
- if (playerController != null)
- {
- playerController.enabled = true;//启用playerController脚本
- }
- }
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。