Skip to content

Instantly share code, notes, and snippets.

@Aaron8052
Last active December 12, 2023 02:06
Show Gist options
  • Save Aaron8052/94655904f8ecafbd8e4d168abc959ea4 to your computer and use it in GitHub Desktop.
Save Aaron8052/94655904f8ecafbd8e4d168abc959ea4 to your computer and use it in GitHub Desktop.
Unity Button 3D
  • 通过Collider实现3D场景中玩家对物体的点击响应
  • refCamera为当前场景中用于捕捉此 3D Button 的摄像机,默认为 Camera.main,可手动指定
  • 需要至少有一种 Collider 组件在 Button3D 上
using System.Collections;
using System.Collections.Generic;
using DancingLine.GameCamera;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
[RequireComponent(typeof(Collider))]
public class Button3D : MonoBehaviour
{
public Camera refCamera;
public bool interactable = true;
public UnityEvent onClick;
Collider _collider;
public LayerMask layerMask;
//StandaloneInputModule _uguiInput;
void Start()
{
refCamera ??= CameraHolder.Instance.MainCamera;
_collider = GetComponent<Collider>();
// _uguiInput = EventSystem.current.GetComponent<StandaloneInputModule>();
_refCameraTrans = refCamera.transform;
_trans = transform;
}
//bool _userClickedInsideColl;
private Transform _refCameraTrans;
private Transform _trans;
void Update()
{
if(!_collider) return;
//_uguiInput.enabled = false;
if (interactable && Input.GetMouseButtonDown(0))
{
var ray = refCamera.ScreenPointToRay(Input.mousePosition);
var distance = Vector3.Distance(_refCameraTrans.position, _trans.position);
if (Physics.Raycast(ray, out var hit, distance, layerMask)) {
if (CompareCollider(hit.collider, _collider))
{
//_userClickedInsideColl = true;
onClick?.Invoke();
}
}
}
/*else if (interactable && _userClickedInsideColl && Input.GetMouseButtonUp(0))
{
Ray ray = refCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit)) {
if (CompareCollider(hit.collider, _collider))
{
_userClickedInsideColl = false;
onClick?.Invoke();
}
}
}
else if(!interactable || !Input.GetMouseButton(0))
{
_userClickedInsideColl = false;
}
_uguiInput.enabled = true;*/
}
bool CompareCollider(Collider a, Collider b)
{
if (!a || !b) return false;
return a == b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment