Skip to content

Instantly share code, notes, and snippets.

@ziriax
Created August 30, 2020 18:46
Show Gist options
  • Save ziriax/ffe861862e21a4d35040394300854c85 to your computer and use it in GitHub Desktop.
Save ziriax/ffe861862e21a4d35040394300854c85 to your computer and use it in GitHub Desktop.
Unity3D mouse to canvas position (dragging item on canvas)
using UnityEngine;
public class MouseDrag : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButton(0))
{
var canvas = transform.root.GetComponent<Canvas>();
var canvasRect = canvas.GetComponent<RectTransform>();
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
canvasRect,
Input.mousePosition,
canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera,
out Vector2 mousePosInCanvasSpace))
{
var selfRect = GetComponent<RectTransform>();
selfRect.localPosition = mousePosInCanvasSpace;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment