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;
    }
}



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值