본문 바로가기
프로그래밍/Unity

Unity - Drag & Drop - How to make Post

by 리나그(ReenAG) 2021. 11. 25.
728x90
반응형

I DO NOT own this logo.

 어떻게 Drag&Drop을 구현하면 좋을지에 대한 포스팅을 해보기로 했다. 이번에 같은 학프하시는 분들에게 도움이 되기를...

 

Drag.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    [SerializeField] public int from;
    private RectTransform rectTransform;
    private CanvasGroup canvasGroup;
    private Vector3 org_pos;

    public void OnBeginDrag(PointerEventData ped){
        //Debug.Log("OnBeginDrag");
        canvasGroup.blocksRaycasts = false;
        canvasGroup.alpha = 0.7f;
    }

    public void OnDrag(PointerEventData ped){
        rectTransform.anchoredPosition += ped.delta;
        //Debug.Log("OnDrag");
    }

    public void OnEndDrag(PointerEventData ped){
        //Debug.Log("OnEndDrag");
        rectTransform.anchoredPosition = org_pos;
        canvasGroup.blocksRaycasts = true;
        canvasGroup.alpha = 1.0f;
    }

    public void SetOrgPos(Vector3 new_pos){
        org_pos = new_pos;
    }

    // Start is called before the first frame update
    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        canvasGroup = GetComponent<CanvasGroup>();
        org_pos = rectTransform.anchoredPosition;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

Drop.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Drop : MonoBehaviour, IDropHandler
{
    [SerializeField] public int to;
    public void OnDrop(PointerEventData ped){
        Drag dragged = ped.pointerDrag.GetComponent<Drag>();

        switch(dragged.from){
            case 1:
                switch(to){
                    case 1:
                        Destroy(dragged);
                        break;
                }
                break;
        }

        Debug.Log(string.Format("dragged {0} to {1}", dragged.from, to));
        dragged.SetOrgPos(GetComponent<RectTransform>().anchoredPosition3D);
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

728x90
반응형