53 lines
1.9 KiB
C#
53 lines
1.9 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace Utils
|
|
{
|
|
public static class DragGhost
|
|
{
|
|
private static GameObject ghost;
|
|
private static Image ghostImage;
|
|
private static Canvas parentCanvas;
|
|
private static CanvasGroup ghostCanvasGroup;
|
|
|
|
// Ensure ghost exists under given canvas
|
|
public static void Show(Canvas canvas, Sprite sprite)
|
|
{
|
|
if (canvas == null || sprite == null) return;
|
|
if (ghost == null || parentCanvas != canvas)
|
|
{
|
|
if (ghost != null) Object.Destroy(ghost);
|
|
parentCanvas = canvas;
|
|
ghost = new GameObject("_SharedDragGhost");
|
|
ghost.transform.SetParent(parentCanvas.transform, false);
|
|
ghostImage = ghost.AddComponent<Image>();
|
|
ghostImage.raycastTarget = false;
|
|
ghostCanvasGroup = ghost.AddComponent<CanvasGroup>();
|
|
ghostCanvasGroup.blocksRaycasts = false;
|
|
ghostCanvasGroup.alpha = 0.5f; // Set transparency to half
|
|
}
|
|
ghostImage.sprite = sprite;
|
|
// set size to sprite rect (avoid SetNativeSize to reduce layout work)
|
|
var rt = ghostImage.rectTransform;
|
|
rt.sizeDelta = new Vector2(sprite.rect.width, sprite.rect.height);
|
|
ghost.SetActive(true);
|
|
}
|
|
|
|
public static void Hide()
|
|
{
|
|
if (ghost != null) ghost.SetActive(false);
|
|
}
|
|
|
|
public static void UpdatePosition(Vector2 screenPosition, Camera cam)
|
|
{
|
|
if (ghost == null || parentCanvas == null) return;
|
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(
|
|
parentCanvas.transform as RectTransform,
|
|
screenPosition,
|
|
cam,
|
|
out Vector2 localPoint);
|
|
ghost.transform.localPosition = localPoint;
|
|
}
|
|
}
|
|
}
|