UNITY之背包管理

来源:互联网 发布:matlab矩阵归一化函数 编辑:程序博客网 时间:2024/06/05 12:01

结构分析:

Inventory------------------->Inventory脚本

      Grid--------------------->背景框

           Cell----------------->InventoryItemGrid脚本

               label------------->显示数量,件数

               Sprite------------>InventoryItem脚本


Inventory脚本

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Inventory : MonoBehaviour {

    public static Inventory _Instance;
    private TweenPosition tweenPosition;
    private bool isShow = false;


//    private int coinCount=1000;
//    public UILabel coinCountLable;
//    public GameObject itemPrefab;
    //存储背包里所有的gird
    public List<InventoryItemGrid> itemGridList = new List<InventoryItemGrid> ();
    // Use this for initialization
    void Start () {
        _Instance = this;
        tweenPosition = GetComponent<TweenPosition> ();
    }
    protected void Show(){
        isShow = true;
        tweenPosition.PlayForward ();
    }

    void Hide(){
        isShow = false;
        tweenPosition.PlayReverse ();
    }
    public void transformState(){
        if (isShow) {
            Hide ();
        } else {
        
            Show ();
        }
    }
}

InventoryItemGrid脚本

using UnityEngine;
using System.Collections;
//3个作用:管理InventoryItem
//1:改变物件在网格中的数量num
//2:使用InventoryItem脚本改变网格中精灵的图片(当物品与物品交换位置时)
//3:改变InventoryItemGrid中的id和num属性值
//改变网格中存放的数据信息
public class InventoryItemGrid : MonoBehaviour {

    public int id = 0;
    public int num = 0;
    private ObjectInfo info = null;
    private UILabel numLabel;
    // Use this for initialization
    void Start () {
    
        numLabel = this.GetComponentInChildren<UILabel> ();
        setId (id,num);
    }
    public void setId(int id,int num=1){
    
        if(id==0){
            return;
        }

        this.id = id;this.num = num;

        info = ObjectsInfo._instance.GetObjectInfoById (id);
        //当网格我空格子时,numlabel在start里初始化时是为null
        //所以当往空网格拖入InventItem时,要从拖入的InventItem中从新获取UIlabel标签
        //因为这时就有UILabel标签类
        numLabel = this.GetComponentInChildren<UILabel> ();

        InventoryItem item = this.GetComponentInChildren<InventoryItem>();
        numLabel.text = this.num.ToString ();
        numLabel.enabled = true;
        item.setId (id);
    }

    public void PlusNum(int num=1){
        this.num += num;
        numLabel.text = this.num.ToString ();
    }

    public void ClearInfo(){
        id = 0;
        num = 0;
        info = null;
        //numLabel.enabled = false;
    }
    // Update is called once per frame
    void Update () {
    
    }
}

InventoryItem脚本

using UnityEngine;
using System.Collections;
public class InventoryItem : UIDragDropItem {

    private UISprite sprite;
    private int id;

    private GameObject objWindowMsg;//要获取的窗口消息预设体
    private GameObject WindowMsg;//实列化的窗口消息预设体对象
    void Awake(){
        //base.Awake();
        sprite = this.gameObject.GetComponent <UISprite>();
        objWindowMsg = Resources.Load<GameObject> ("WindowMsg");

    }

    public void setId(int id){
        ObjectInfo info = ObjectsInfo._instance.GetObjectInfoById (id);

        if(info==null){
            sprite.spriteName = null;
            this.id = id;
            return;
        }
        sprite.spriteName = info.iconName;
        this.id = id;
    }

    //背包物品移动规则
    /*
     * 第一种情况:当物品与物品交换时,即拖动的InventItem与InventItem相撞(交换),
     *           只需交换下InventoryItemGrid中的数据,InventoryItemGrid是管理InventoryItem
     * 第二中情况:当物品放入空网格中时,将物品的归属者重新定义为空网格所有
     *           即this.transform.SetParent (surface.transform);
     *           newGrid.setId (oldGrid.id, oldGrid.num);对添加进了的物品,进行更改信息配置
     *           这样就将InventoryItem所挂载的物品移动空网格中去了,原来的格子则变为空网格进行oldGrid.ClearInfo ();
     *           清除原来网格中的信息配置
     * 第三种情况:不与物品交换,又不拖入空网格中,属于四处乱拖的则鼠标拖放释放后直接回到原来位置ResetPosition();
     * 
    */

    protected override void OnDragDropRelease (GameObject surface)
    {
        base.OnDragDropRelease (surface);

        if (surface != null) {
            //拖放到一个有物体的格子
            if (surface.tag == Tags.INVENTORY_ITEM) {
                print ("INVENTORY_ITEM");

                InventoryItemGrid oldGrid = this.transform.parent.GetComponent<InventoryItemGrid> ();
                int id = oldGrid.id;
                int num = oldGrid.num;
                InventoryItemGrid newGrid = surface.transform.parent.GetComponent<InventoryItemGrid> ();
                //交换数据
                oldGrid.setId (newGrid.id, newGrid.num);
                newGrid.setId (id, num);
                ResetPosition ();
            }
            //拖放到一个空格子
            else if (surface.tag == Tags.INVENTORY_ITEM_GRID) {

                print ("INVENTORY_ITEM_GRID");
                //拖到自己的格子
                if (surface.transform.parent == this.transform.parent) {
                    ResetPosition ();
                } else {//其他空格子
                
                    print ("INVENTORY_ITEM_GRID");

                    InventoryItemGrid oldGrid = this.transform.parent.GetComponent<InventoryItemGrid> ();
                    InventoryItemGrid newGrid = surface.transform.GetComponent<InventoryItemGrid> ();

                    //this.transform.SetParent (surface.transform);
                    //这两句是一个意思:从新设置InventItem的父对象是谁,即从新归属于谁
                    this.transform.parent = surface.transform;
                    ResetPosition ();
                    //空网格中拖入了InventItem,就要去修改InventItem的父类中的属性,即网格中的属性
                    //因为有东西了,就要去修改相应的配置
                    newGrid.setId (oldGrid.id, oldGrid.num);
                    oldGrid.ClearInfo ();
                }
            } else {
            
                ResetPosition ();
            }
        } else {
        
            ResetPosition ();
        }
    }

    void ResetPosition(){
        transform.localPosition = Vector3.zero;
    }
    //使用UIEventTrigger对事件进行监听触发
    //监听OnHoverOver事件,调用此函数
    public void Show(){
    
        //在此对象下初始化一个objWindowMsg的预设体
        WindowMsg= NGUITools.AddChild (this.gameObject,objWindowMsg);
        //设置预设体的位置
        WindowMsg.transform.localPosition = new Vector3 (152,-91,0);
        //调用预设体中的MsgLoad脚本的show方法进行消息显示
        WindowMsg.GetComponent<MsgLoad> ().Show (id);
    }

    //监听UIEventTrigger中的OnHoverOut和OnReLease事件调用此函数
    //监听OnReLease是因为拖动变化位置时objWindowMsg预设体已经被创建出来,
    //拖到另一个位置时就属于其一部分,所以为了消除此WindowMsg消息窗口,进行监听OnReLease事件
    public void Hide(){
        if(WindowMsg!=null){
            Destroy (WindowMsg);
        }
    }
}

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/*
 * 将存储信息文件的数据加载到字典中去
 * 提供根据id获取信息的方法
 * 即读信息
*/
public class ObjectsInfo : MonoBehaviour {

    public static ObjectsInfo _instance;
    public TextAsset objectsInfoListText;//通过连线方式获取(拖ObjectsInfoList.txt到此)
    public Dictionary<int,ObjectInfo> objectInfoDirctionary=new Dictionary<int, ObjectInfo>();

    void Awake(){
        _instance = this;
        ReadInfo ();

        foreach(var e in objectInfoDirctionary){
            print (e);
        }
    }
    public ObjectInfo GetObjectInfoById(int id){
        ObjectInfo info = new ObjectInfo ();
        objectInfoDirctionary.TryGetValue (id,out info);
        return info;
    }
    public void ReadInfo(){
        string text = objectsInfoListText.text;
        string[] strArray = text.Split ('\n');
        foreach(string str in strArray){
            string[] proArray = str.Split (',');
            ObjectInfo info = new ObjectInfo ();
            int id = int.Parse (proArray[0]);
            string name = proArray [1];
            string iconName = proArray [2];
            string typeStr = proArray [3];

            info.id = id;
            info.name = name;
            info.iconName = iconName;
            ObjectType type = ObjectType.Drug;
            switch(typeStr){
            case "Drug":
                type = ObjectType.Drug;
                break;
            case "Equip":
                type = ObjectType.Equip;
                break;
            case "Mat":
                type = ObjectType.Mat;
                break;
            }

            info.type = type;
            if(type==ObjectType.Drug){

                int hp = int.Parse (proArray[4]);
                int mp = int.Parse (proArray[5]);
                int priceSell = int.Parse (proArray[6]);
                int priceBuy = int.Parse (proArray[7]);
                info.hp = hp;
                info.mp = mp;
                info.priceBuy = priceBuy;
                info.priceSell = priceSell;
            }
            //添加到字典中,方便根据id进行查找
            objectInfoDirctionary.Add (id,info);
        }
    }
}

using UnityEngine;
using System.Collections;
//对每条文件信息构化成一个类对象
public enum ObjectType{
    Drug,
    Equip,
    Mat
}
//id,名称,icon名称,类型,加血值,加蓝值,卖出价,买入价
public class ObjectInfo  {
    public int id;
    public string name;
    public string iconName;
    public ObjectType type;
    public int hp;
    public int mp;
    public int priceSell;
    public int priceBuy;
}

using UnityEngine;
using System.Collections;
//标签信息管理
public class Tags : MonoBehaviour {
    public const string GROUND="Ground";
    public const string PLAYER="Player";
    public const string INVENTORY_ITEM="InventoryItem";
    public const string INVENTORY_ITEM_GRID="InventoryItemGrid";
}

//ObjectsInfoList.txt

1001,小血评,Orc Armor - Boots,Drug,50,0,50,60
1002,大血瓶,Orc Armor - Bracers,Drug,100,0,70,100
1003,蓝瓶,Orc Armor - Shoulders,Drug,0,100,60,80

0 0