using EasyInject.Attributes; using NUnit.Framework; using System.Collections.Generic; using UnityEngine; /// /// 监听处理组件 /// [GameObjectBean] public sealed class EventCompent : MonoBehaviour { private float lastClickTime = 0f; private const float DOUBLE_CLICK_INTERVAL = 0.5f; public delegate void MouseClickEvent(); public event MouseClickEvent MouseClickEvents; public event MouseClickEvent MouseDoubleClickEvents; private void Start() { List mouseClicks = ApplicationBoot.Instance.GetBeans(); foreach (IMouseClick click in mouseClicks) { MouseClickEvents += click.MouseSingleClick; MouseDoubleClickEvents += click.MouseDoubleClick; } } private void Update() { GlobalMouseRayHandle(); } /// /// 全局射线点击监听 /// private void GlobalMouseRayHandle() { if (Input.GetMouseButtonDown(0)) { CheckDoubleClick(); } } void CheckDoubleClick() { // 双击时执行的操作(如创建物体) Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { float currentTime = Time.time; if (currentTime - lastClickTime <= DOUBLE_CLICK_INTERVAL) { // 双击事件 OnDoubleClick(hit); return; } else { // 单击事件 OnSingleClick(hit); } lastClickTime = currentTime; } } private void OnDoubleClick(RaycastHit hit) { GameObject clickTarget = hit.collider.gameObject; MonoBehaviour[] monoBehaviours = clickTarget.GetComponents(); if(monoBehaviours == null) { return; } if ( monoBehaviours.Length < 1) { MonoBehaviour[] monos = clickTarget.GetComponentsInParent(); CheckDoubleClickTrigger(monos); } else { CheckDoubleClickTrigger(monoBehaviours); } } private void OnSingleClick(RaycastHit hit) { // 单击时执行的操作 GameObject clickTarget = hit.collider.gameObject; MonoBehaviour[] monoBehaviours = clickTarget.GetComponents(); if (monoBehaviours == null) { return; } if (monoBehaviours.Length < 1) { MonoBehaviour[] monos = clickTarget.GetComponentsInParent(); CheckSingleClickTrigger(monos); } else { CheckSingleClickTrigger(monoBehaviours); } } private void CheckDoubleClickTrigger(MonoBehaviour[] behaviours) { foreach (var ev in MouseDoubleClickEvents?.GetInvocationList()) { if (ev.Target is MonoBehaviour mono) { foreach(var behav in behaviours) { if (mono == behav) { ev.DynamicInvoke(); } } } } } private void CheckSingleClickTrigger(MonoBehaviour[] behaviours) { foreach (var ev in MouseClickEvents?.GetInvocationList()) { if (ev.Target is MonoBehaviour mono) { foreach (var behav in behaviours) { if (mono == behav) { ev.DynamicInvoke(); } } } } } }