[unity]NGUI实现背包拖拽+使用EventDelegate回调

来源:互联网 发布:qq淘宝优惠群怎么做 编辑:程序博客网 时间:2024/05/22 17:28

一、使用的NGUI工具类

UIGrid
UIScrollView
UIDragScrollView
UIDragDropItem
UIDragDropContainer
UIDragDropRoot

UIScrollView可以上下拉动背包的容器。
UIGrid配合UIScrollView实现格子自动排列排序。
UIDragDropItem背包格子拖动类。
UIDragScrollView可以拖着格子实现下拉。
UIDragDropContainer是背包格子拖动接收类。
UIDragDropRoot格子拖动时复制体容器。

二、背包拖动

这里写图片描述

scrollview的Inspector

这里写图片描述
scrollview是背包的地图也是背包的容器
加入UIScrollView之后会自动加入一个UIPanel。UIScrollView可以指定一个横向和纵向的ScrollBar。

listGrid的Inspector

这里写图片描述
要实现排序的话Sorting要设置不为Non
代码中指定一个排序方法

    transform.GetComponent<UIGrid>().onCustomSort = func;    int func(Transform a ,Transform b)    {        return 0;    }

拖拽的Item

这里写图片描述

using UnityEngine;using System.Collections;//继承UIDragDropItem,为了指定一个回调的EventDelegate,同时加了一个自定义的参数typepublic class UIDropCardItem : UIDragDropItem {    public EventDelegate call;    public int type;    //拖拽释放后触发    protected override void OnDragDropRelease (GameObject surface)    {// 判断是否在一个容器上释放        if (surface != null &&surface.GetComponent<UIDragDropContainer>()!=null )            {        //surface是接收拖拽的容器                call.Execute();               // 执行回调            }        base.OnDragDropRelease(surface);    }}

创建一个格子,设置delegate

 go = GameObject.Instantiate(Resources.Load<GameObject>("prefab/LibItem")) as GameObject; tran.GetComponent<UIGrid>().AddChild(go.transform); go.transform.localScale = new Vector3(1,1,1);//不用nguiTools加的话要重设置一下缩放比例 go.GetComponent<UISprite>().spriteName = "card" + ids[i]; UIDropCardItem drag = go.AddComponent<UIDropCardItem>(); drag.type = ids[i]; drag.cloneOnDrag = true; drag.call = new EventDelegate(this, "TeamChange"); EventDelegate ed = new EventDelegate(this, "LibCardClick"); ed.parameters[0] = new EventDelegate.Parameter(drag, "type"); 

UIDragDropContainer和UIDragDropRoot

UIDragDropContainer加入到接收拖拽的容器就好了,就是UIDropCardItem 类里的surface,可以再UIDropCardItem 拖拽释放的时候设置一些图片、音效。

UIDragDropRoot找个GameObject加进去。UIDragDropItem 的cloneOnDrag 不为true的话不加也行。

0 0
原创粉丝点击