'How to reset back position of a dragging object, if the dragging object dont met IDropHandler script containing object
In Unity i am using IBeginDragHandler, IDragHandler, IEndDragHandler to drag and drop object. it's working fine. My need is to reset the position of the draggable object to the starting position if it doesn't touch another object that contains IDropHandler. below is my code
Drag script:-
using UnityEngine.EventSystems;
public class Compiler_Drag : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler
{
[SerializeField] private Canvas canvas;
private RectTransform rectTransform;
private CanvasGroup canvasGroup;
Vector3 myPosition;
// Start is called before the first frame update
void Start()
{
myPosition = this.gameObject.transform.position;
}
private void Awake()
{
rectTransform =GetComponent<RectTransform>();
canvasGroup = GetComponent<CanvasGroup>();
}
// Update is called once per frame
void Update()
{
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
canvasGroup.alpha = .6f;
canvasGroup.blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("OnDrag");
rectTransform.anchoredPosition +=eventData.delta/ canvas.scaleFactor;
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag");
canvasGroup.alpha = 1f;
canvasGroup.blocksRaycasts = true;
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("OnPointerDown");
}
}
> Drop object script:-
using UnityEngine.EventSystems;
public class Compiler_Drop_Handler : MonoBehaviour, IDropHandler
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnDrop(PointerEventData eventData)
{
Debug.Log("OnDrop");
if(eventData.pointerDrag !=null)
{
eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
}
}
}
what I need is that I should be only able to drop the dragging object, to the object that contains/is attached to the second script.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
