Hi, I am trying to return a draggable object (Image) to its original position whenever the user “drops” it. I already have a good start to the drag & drop script, but setting the original position of the object in the OnEndDrag() just puts it in the center of the screen and not in the original location. This is the drag & drop script (the commented stuff was for testing and didn’t help):
public class DragDrop : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler
{
[SerializeField] private Canvas rootCanvas;
private RectTransform rectTransform;
private CanvasGroup canvasGroup;
public Vector2 originalPosition;
public Vector3 original3d;
public int centerCardNum; // specified in Unity
void Awake() {
rectTransform = GetComponent<RectTransform>();
canvasGroup = GetComponent<CanvasGroup>();
var taggedObjects = GameObject.FindGameObjectsWithTag("rootCanvas");
if (taggedObjects.Length == 0) {
Debug.Log("Error: DragDrop: Awake: No objects found with tag 'rootCanvas'");
return;
}
rootCanvas = taggedObjects[0].GetComponent<Canvas>();
originalPosition = rectTransform.anchoredPosition;
original3d = rectTransform.anchoredPosition3D;
}
public void OnBeginDrag(PointerEventData eventData) {
canvasGroup.blocksRaycasts = false;
canvasGroup.alpha = 0.6f;
}
public void OnDrag(PointerEventData eventData) {
rectTransform.anchoredPosition += eventData.delta / rootCanvas.scaleFactor;
}
public void OnEndDrag(PointerEventData eventData) {
canvasGroup.blocksRaycasts = true;
canvasGroup.alpha = 1f;
// GetComponent<Transform>().SetParent(GameObject.Find("CenterCardsCanvas").GetComponent<Transform>());
// GetComponent<Transform>().SetSiblingIndex(0);
// GetComponent<RectTransform>().SetParent(GameObject.Find("CenterCardsCanvas").GetComponent<RectTransform>());
// GetComponent<RectTransform>().SetSiblingIndex(0);
rectTransform.anchoredPosition3D = original3d;
}
public void OnPointerDown(PointerEventData eventData) {
Debug.Log("OnPointerDown");
}
}
See line 21 where you mark the original positions in Awake()?
I believe you actually want to store those original positions (or make fresh equivalent variables called “PreDrag”, not sure what you want “original” to mean here) at the start of the OnBeginDrag() process.
Exactly what I needed, thank you. I moved line 22 into OnBeginDrag(). I guess the issue was that the desired anchored position wasn’t available from Awake().