此方法只需在相机处实现(单击,双击.....)操作,无需在每个物体写(单击,双击....)事件,实现一个鼠标动作执行不同物体的不同方法
- 编写一个基类接口,预写(双击,单击)方法
- 物体脚本继承接口,基类接口无需挂载
- 相机射线通过接口获取组件再实现方法,这样可以通过接口统一获取组件
- 基类接口
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();
}
}
}
}