天天看點

Unity插件NGUI實作背包系統

                 三十 背包系統的制作

1 建立一個Sprite作為背景圖檔

2 建立一個Sprite作為格子并儲存為Prefab

3 在格子下建立Sprite作為物品

4 在物品下建立Label用來顯示物品個數

5 把物品做成Prefab

Unity插件NGUI實作背包系統

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并指定給相應對象

繼續閱讀