82 lines
2.6 KiB
C#
82 lines
2.6 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
|
|
public class DraggableUI : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
|
|
{
|
|
private RectTransform rectTransform;
|
|
private Canvas canvas;
|
|
private CanvasGroup canvasGroup;
|
|
private Vector2 pointerStartLocalCursor; //The initial pointer position when the drag starts
|
|
private bool isDragging = false; //Flag to check if a component is being dragged
|
|
|
|
private SettingsHandler settingsHandler; // Reference to SettingsHandler
|
|
public GameSettings gameSettings; // Reference to GameSettings
|
|
|
|
void Start()
|
|
{
|
|
rectTransform = GetComponent<RectTransform>();
|
|
canvas = GetComponentInParent<Canvas>();
|
|
canvasGroup = GetComponent<CanvasGroup>();
|
|
|
|
// Find SettingsHandler in the scene or use another method to get reference
|
|
settingsHandler = FindObjectOfType<SettingsHandler>();
|
|
}
|
|
|
|
|
|
// Function for initial when gameobject is pressed on
|
|
public void OnPointerDown(PointerEventData eventData)
|
|
{
|
|
//converts the screen point where the pointer was pressed to a local point within the rectangle
|
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out pointerStartLocalCursor);
|
|
|
|
canvasGroup.blocksRaycasts = false;
|
|
isDragging = false;
|
|
}
|
|
|
|
|
|
// Function for when a gameobject is being dragged
|
|
public void OnDrag(PointerEventData eventData)
|
|
{
|
|
isDragging = true;
|
|
Vector2 localPointerPos;
|
|
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, eventData.position, eventData.pressEventCamera, out localPointerPos))
|
|
{
|
|
rectTransform.localPosition = localPointerPos - pointerStartLocalCursor;
|
|
}
|
|
}
|
|
|
|
|
|
// Function for when a gameobject is released, after being dragged
|
|
public void OnPointerUp(PointerEventData eventData)
|
|
{
|
|
canvasGroup.blocksRaycasts = true;
|
|
|
|
if (!isDragging)
|
|
{
|
|
// Simulate a button click
|
|
Button button = GetComponent<Button>();
|
|
if (button != null)
|
|
{
|
|
button.onClick.Invoke();
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// Function to Save Control Settings
|
|
void SaveSettings()
|
|
{
|
|
if (settingsHandler != null)
|
|
{
|
|
settingsHandler.SaveSettings(); // Call SaveSettings from SettingsHandler
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("SettingsHandler reference is null.");
|
|
}
|
|
}
|
|
}
|