UGUI EventSystems UI拖拽

UGUI中 关于事件的触发,它给我们提供了大概十七个接口可用来使用,各个接口的作用以及实现方法可以查阅Unity官方API:

file:///D:/Unity5.0.1/Unity/Editor/Data/Documentation/en/ScriptReference/index.html。想看具体的例子可以借鉴Unity提供的UGUI官方实例:http://pan.baidu.com/s/1mgmpgHM

里面也有做好的拖拽实例。这边我贴出简单的拖拽代码,能够让你更容易看懂实例:

完成拖拽需要两个脚本   一个是drag对象 , 一个是drop对象:


using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class dragme : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler
{
    //生成的icon
    private GameObject draged_icon;

    public void OnBeginDrag(PointerEventData eventData)
    {
       //设置icon属性,添加组件
        draged_icon = new GameObject("icon");
        draged_icon.transform.SetParent(GameObject.Find("Canvas").transform, false);

        draged_icon.AddComponent<RectTransform>();
        draged_icon.AddComponent<Image>();
        draged_icon.GetComponent<Image>().sprite = GetComponent<Image>().sprite;

        //让图标不执行事件检测,防止icon妨碍后面的event system
        CanvasGroup group = draged_icon.AddComponent<CanvasGroup>();
        group.blocksRaycasts = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        //在RectTransform下 实现鼠标 物体的跟随效果
        Vector3 worldpos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(draged_icon.GetComponent<RectTransform>(), eventData.position, Camera.main, out worldpos))
        {
            draged_icon.transform.position = worldpos;
        }

    }

    public void OnEndDrag(PointerEventData eventData)
    {
        //销毁图标
        if (draged_icon != null)
        {
            Destroy(draged_icon.gameObject);
        }
    }
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Dropme : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler,IDropHandler
{
    //鼠标进入
    public void OnPointerEnter(PointerEventData eventData)
    {
       //有拖拽物,drop区域变色,否则return
        GameObject dragobj = eventData.pointerDrag;

        if (dragobj == null) return;

        GetComponent<Image>().color = Color.grey;
    }

    //鼠标离开 重置颜色white
    public void OnPointerExit(PointerEventData eventData)
    {
        GetComponent<Image>().color = Color.white;
    }

    //drop 赋予拖拽物体sprite
    public void OnDrop(PointerEventData eventData)
    {
        GameObject dragobj = eventData.pointerDrag;

       // if (dragobj == null) return;

        GetComponent<Image>().sprite = dragobj.GetComponent<Image>().sprite;

        GetComponent<Image>().color = Color.white;
    }
}

UGUI EventSystems UI拖拽_第1张图片 UGUI EventSystems UI拖拽_第2张图片 UGUI EventSystems UI拖拽_第3张图片


你可能感兴趣的:(拖拽,UGUI,EventSystems)