背包系统(二)

来源:互联网 发布:淘宝网云客服干什么 编辑:程序博客网 时间:2024/06/13 01:21
背包系统(二)
7、拖入两个物品预设体到格子里面,并为其添加数量

8、修改物品脚本,实现两个物品可以交换

 //重写OnDragDropRelease方法

    protected override void OnDragDropRelease(GameObject surface)

    {

        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;//把第一个背包居中

        }

    }

9、修改格子脚本,实现按下F键,随机产生物品

public GameObject[] cells;//9个格子

    public string[] knapsacksName;//三个物品的名称

    public GameObject item;//任意一个物品


    void Update() { 

        if(Input.GetKeyDown(KeyCode.F)){//按下F键

            PickUp();//调用 PickUp()

        }

    }


    void PickUp() {

        int index = Random.Range(0, knapsacksName.Length);//随机生成0,1,2三个数其中一个

        string name = knapsacksName[index];//得到随机的物品名称

        for (int i = 0; i < cells.Length; i++)

        {

            if (cells[i].transform.childCount == 0)//当前格子里面没有物品

            {

                GameObject go = NGUITools.AddChild(cells[i], item);//把新生成的物品放入格子里面

                

                go.GetComponent<UISprite>().spriteName = name;//为新生成的物品添加名称

                go.transform.localPosition = Vector3.zero;//把物品居中

                break;

            }

        }

}

0 0