unity小白简单鼠标交互:鼠标和3D物体交互

此方法只需在相机处实现(单击,双击.....)操作,无需在每个物体写(单击,双击....)事件,实现一个鼠标动作执行不同物体的不同方法

  1. 编写一个基类接口,预写(双击,单击)方法
  2. 物体脚本继承接口,基类接口无需挂载
  3. 相机射线通过接口获取组件再实现方法,这样可以通过接口统一获取组件

  • 基类接口
using System.Collections;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using UnityEngine;

public interface bace 
{
    public void say()
    {
        
    }

}

  • 物体脚本 
    • 物体脚本继承接口实现方法
    • 物体上需要加collider(碰撞体)用于相机射线检测
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class Cube1 : MonoBehaviour,bace
{
    
    public void say()
    {
        print("box1");
    }
}

  • 相机脚本 
    • 射线检测到就执行当前物体继承接口实现的方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseClick : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                hit.collider.GetComponent<bace>().say();
            }
        }
        
      
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值