42 lines
1.2 KiB
C#
42 lines
1.2 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
public class PlayerRaycastOnUI : MonoBehaviour
|
|
{
|
|
public Camera playerCamera;
|
|
public Canvas worldCanvas;
|
|
public KeyCode interactKey = KeyCode.E;
|
|
|
|
private GraphicRaycaster raycaster;
|
|
private EventSystem eventSystem;
|
|
|
|
void Start()
|
|
{
|
|
raycaster = worldCanvas.GetComponent<GraphicRaycaster>();
|
|
eventSystem = EventSystem.current;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
// Ñòâîðþºìî PointerEventData íà îñíîâ³ öåíòðó êàìåðè
|
|
PointerEventData pointerData = new PointerEventData(eventSystem);
|
|
pointerData.position = playerCamera.WorldToScreenPoint(playerCamera.transform.position + playerCamera.transform.forward * 2f);
|
|
|
|
List<RaycastResult> results = new List<RaycastResult>();
|
|
raycaster.Raycast(pointerData, results);
|
|
|
|
foreach (var result in results)
|
|
{
|
|
Button button = result.gameObject.GetComponent<Button>();
|
|
if (button != null)
|
|
{
|
|
if (Input.GetKeyDown(interactKey))
|
|
{
|
|
button.onClick.Invoke();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|