Rect Transform Start position

Hey guys,

I’m trying to create some sort of drag’n’drop UI element.

So I have an UI image that is under an UI object with “Grid Layout Group (script)” not sure if it’s relevant, but telling it to be sure.

When I drag the Image over the screen it is following my mouse (this works)
But when I release the image I want it to snap back to it’s original position.

So I need to store the start position of this rect transform. But always seem to snap to a position that is not where the image started.

Anybody knows how to get the right start pos out of a rect transform? :slight_smile:

Yep, I just record the start position of the transform and when the pointer lifts it snaps back to that point:

	public void OnPointerDown(PointerEventData ped) 
		mouseDown = true;
		startPos = transform.position;
		startMousePos = Input.mousePosition;

	public void OnPointerUp(PointerEventData ped) 
		mouseDown = false;

			transform.position = startPos;

You’ll have to fix it in with your code though, just tested it with a grid layout and it appears to work.

Okay so I got it to work :smiley: I hope there’s a cleaner way of doing this but just resetting the parent of the element you want to snap back to its original position works for me. You also have to set its child sibling index too so it’s at the right place of your gird after reparenting.

        public void Init()
            m_rectTransform = transform as RectTransform;
            m_startPos = m_rectTransform.localPosition;

            m_gridPos = transform.GetSiblingIndex();

        public void OnPointerUp(PointerEventData eventData)
            m_rectTransform.localPosition = m_startPos;

            // Hackxor fix
            Transform parent = m_rectTransform.parent;
            m_rectTransform.parent = null;
            m_rectTransform.parent = parent;