Unity插件NGUI实现背包系统

来源:互联网 发布:linux sendmail smtp 编辑:程序博客网 时间:2024/05/17 03:37

                  背包系统的制作

1 创建一个Sprite作为背景图片

2 创建一个Sprite作为格子并保存为Prefab

3 在格子下创建Sprite作为物品

4 在物品下创建Label用来显示物品个数

5 把物品做成Prefab

 

7 给物品添加Box Collider

8 创建脚本继承UIDragDropItem指定给物品

using UnityEngine;

using System.Collections;

public class KnapsackItem : UIDragDropItem {

    protected override void OnDragDropRelease(GameObject surface)

    {

        base.OnDragDropRelease(surface);

        Debug.Log(surface.transform.childCount);//显示格子下面子物体有多少个

        //if (surface.transform.childCount > 0)//当物品大于零时

        if(surface.tag=="Ceil")//当格子上有物体时,surface将会改变,故用此来判断是否已经有物品

        {//没有物品时

            this.transform.parent = surface.transform;//将物品移到格子下边

            this.transform.localPosition = Vector3.zero;//设置局部坐标为0,此时可以居中

        }

        else if(surface.tag=="KnapsackItem")

        {//有物品时,进行交换

            Transform parent = surface.transform.parent;//过度,将格子上的当前物品位置保存

            surface.transform.parent = this.transform.parent;//将已经在格子上的物品移动到要交换的物品的格子

            surface.transform.localPosition = Vector3.zero;//设置局部坐标为0\

            this.transform.parent = parent;//把要交换的格子移过去

            this.transform.localPosition = Vector3.zero;

        }

    }

}

9 创建脚本指定给格子

代码设计:

using UnityEngine;

using System.Collections;

public class KnapSack : MonoBehaviour {

   public GameObject[] Ceils=new GameObject[16];//用来存放物品的格子数组

 }     

10 给格子进行编号并将格子复制给Ceils数组

11 设置Tag并指定给相应对象

1 1