自用的点击3D模型触发方法(可拖拽方法)

就是可以像按钮一样,拖拽点击方法,当你点击模型的时候,可以点击触发方法(目前自用)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UIElements;

public class Clickmodel : MonoBehaviour
{
    public UnityEvent onClick;
    public Camera Main_Camera;

    public Collider Have_Collider;

    public MouseButton mouseButton = MouseButton.Left; 
    private void OnEnable()
    {
        Main_Camera = GetBestCamera();
        Have_Collider =GetComponent<Collider>();
        if (Have_Collider == null)
        {
            Debug.Log("没有任何碰撞体");
        }
        else if(Have_Collider.enabled == false)
        {
            Debug.Log("碰撞体没有被启用");
        }

        if(Main_Camera == null)
        {
            Debug.Log("没有主摄像机");
        }
        else if (Main_Camera.enabled == false)
        {
            Debug.Log("主摄像机没有被使用");
        }
    }
    /// <summary>
    ///获取场景中所有的摄像机如果只有一个摄像机,直接返回  
    ///如果有多个摄像机,找到 Depth 值最高的摄像机
    /// </summary>
    /// <returns></returns>
    Camera GetBestCamera()
    {
 
        Camera[] cameras = FindObjectsOfType<Camera>();

        if (cameras.Length == 0)
        {
            Debug.LogError("场景中没有摄像机!");
            return null;
        }

   
        if (cameras.Length == 1)
        {
            return cameras[0];
        }


        Camera bestCamera = cameras[0];
        foreach (Camera cam in cameras)
        {
            if (cam.depth > bestCamera.depth)
            {
                bestCamera = cam;
            }
        }

        return bestCamera;
    }
    // 定义鼠标按键枚举
    public enum MouseButton
    {
        Left = 0,    // 左键
        Right = 1,   // 右键
        Middle = 2    // 中键
    }

    void Update()
    {
        // 将枚举值转换为 int,用于 Input.GetMouseButtonDown
        if (Input.GetMouseButtonDown((int)mouseButton)) // 检测指定的鼠标按键
        {
            Ray ray = Main_Camera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            Debug.DrawRay(ray.origin, ray.direction * 100, Color.red, 1.0f); // 调试射线

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.gameObject == gameObject) // 检查是否点击了当前模型
                {
                    Debug.Log("点击模型");
                    onClick?.Invoke(); // 触发事件
                }
            }
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值