1.新建一个Sprite(鞋子)
2.添加Box Collider添加Drag Drop Item
3.添加3个Sprite(格子)
4.把shoe拖拉到Sprite上面,把number(物品的个数)拖拉到Label)
删除UIDrag Drop Item,创建一个脚本放到鞋子上,当把鞋子放到格子上时就可以看到控制台打印信息。
protected override void OnDragDropRelease(GameObject surface)
{ //重写OnDragDropRelease方法
base.OnDragDropRelease(surface);//调用父类的OnDragDropRelease(surface)方法
this.transform.parent = surface.transform; //把物品放入格子里面
this.transform.localPosition = Vector3.zero;//把物品居中
把shoe放入prefabs文件夹中,然后删掉shoe-->给每一个knapsack都添加Box Collider-->编写一个脚本然后拖拉到bg(背景)上面-->把bg属性Cells的Size大小设置为9-->把每个knapsack分别拖拉到对应的Element里面
public class MyKnapsack : MonoBehaviour {
public GameObject[] cells;
}
修改脚本KnapsackItem ,当拖拉鞋子到各个格子里面时默认都居中
public class KnapsackItem : UIDragDropItem {
protected override void OnDragDropRelease (GameObject surface)
{
base.OnDragDropRelease (surface);
this.transform.parent = surface.transform;
this.transform.localPosition = Vector3.zero;
}
}
交换鞋子
把两只鞋子(shoe)分别放到两个背包(knaspack)里面-->添加两个标签(没有放鞋子的背包的标签是Cell 放鞋子的鞋子的标签是Knaspack)
public class KnapsackItem : UIDragDropItem
//必须继承UIDragDropItem
{
protected override void OnDragDropRelease(GameObject surface)
{
//重写OnDragDropRelease方法
base.OnDragDropRelease(surface);
//调用父类的OnDragDropRelease(surface)方法
if (surface.tag == "Cell") {
this.transform.parent = surface.transform;
//把物品放入格子里面
this.transform.localPosition = Vector3.zero;
//把物品居中
}
else if(surface.tag =="Knapsack"){
//第一个背包:拖动的背包
//第二个背包:将要被交换的背包
Transform parent = surface.transform.parent;
//得到第二个格子Transform对象
surface.transform.parent = this.transform.parent;
//把第二个背包放入第一个格子里面
surface.transform.localPosition = Vector3.zero;
//把第二个背包居中
this.transform.parent = parent;
//把第一个背包放入第二个格子里面
this.transform.localPosition = Vector3.zero;
//把第一个背包居中
}
}
}
更多精彩关注:http://www.gopedu.com/