unity ngui学习(五)

unity背包

新建一个精灵当做背景,在里面放一些小方格图片精灵


在背景脚本下写

    public GameObject[] cells;
    public string[] equipmentsName;
    public GameObject item;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.X))
        {
            Piclup();
        }
    }
    public void Piclup()
    {
        int index = Random.Range(0, equipmentsName.Length);
        string name = equipmentsName[index];
        bool isFind = false;

        for (int i = 0; i < cells.Length; i++)
        {
            if (cells[i].transform.childCount > 0)//判断当前格子有没有物品
            {
                //如果有的话 判断当前游戏物品的名字
                MyDropDrags item= cells[i].GetComponentInChildren<MyDropDrags>();
                //判断当前游戏物体名字跟我们捡到的游戏名字是否一样
                if (item.sprite.spriteName == name)
                {
                    isFind = true;
                    item.AddCount(1);
                    break;
                }
            }
        }
        if (isFind == false)
        {
            for (int i = 0; i < cells.Length; i++)
            {
                if (cells[i].transform.childCount == 0)
                {
                    //当前位置没有物品
                    //添加我们新捡起来的物品
                    GameObject go = NGUITools.AddChild(cells[i], item);
                    go.transform.localPosition = Vector3.zero;
                    break;
                }
            }
        }        
    }

奖励物品 添加碰撞器,新建脚本


public class MyDropDrags : UIDragDropItem
{

    public UISprite sprite;
    public UILabel lable;
    private int count = 1;

    public void AddCount(int number = 1)
    {
        count += number;
        lable.text = count + "";
    }
    protected override void OnDragDropRelease(GameObject surface)
    {
        base.OnDragDropRelease(surface);
        //if (surface.transform.childCount > 0)
        //{
        //    //交换物品
        //}
        //else
        //{
        //    this.transform.parent = surface.transform;
        //    this.transform.localPosition = Vector3.zero;
        //}

        this.transform.parent = surface.transform;
        this.transform.localPosition = Vector3.zero;

        if (surface.tag == "cell")
        {
            this.transform.parent = surface.transform;
            this.transform.localPosition = Vector3.zero;
        }
        else if(surface.tag== "knapsckItem")
        {
            //交换位置
            Transform parent = surface.transform.parent;
            surface.transform.parent = this.transform.parent;
            surface.transform.localPosition = Vector3.zero;
            this.transform.parent = parent;
            this.transform.localPosition = Vector3.zero;
        }

    }

Script 当前脚本

Sprite 背包奖励

lable 数量

猜你喜欢

转载自blog.csdn.net/u010773333/article/details/50955708