NGUI背包中整理背包的两种方法

  

  方法一:

  遍历物品格子的数组,提取出每一个子对象并存入一个集合后,遍历物品格子数组,把每一个集合中的物体元素用NGUI.AddChild方法添加到格子下。

          

 //方法1:使用重新排序,有问题
        foreach (GameObject cell in cells)
        {
            if (cell.transform.childCount > 0)
            {
                itemList.Add(cell.transform.GetChild(0).gameObject);

                cell.transform.DestroyChildren();
            }
        }

        int count = 0; //计数器

        foreach (var item in itemList)
        {
            GameObject obj = NGUITools.AddChild(cells[count], item);
            obj.GetComponent<UISprite>().enabled = true;
            obj.GetComponent<ItemDrag>().enabled = true;
            obj.GetComponentInChildren<UISprite>().enabled = true;
            count++;
        }

  在使用第一种方法后,出现了一个问题,原本在预制体上的组件都处于不激活状态,虽然实现了重新排序,但需要把子物体中的组件重新激活。

方法二:

  使用类似冒泡排序的算法,冒泡排序回顾:

  https://www.cnblogs.com/shen-hua/p/5422676.html

  在整理背包的过程中,如果前一个格子没有子物体,那么就把后一个格子子物体父级设置给前一个空的格子。

  

 
 
 for (int i = 0; i < cells.Length; i++)
        {
            for (int j = 0; j < cells.Length-1; j++)
            {
                //Cells[j]为格子数组
                if (cells[j].transform.childCount<cells[j+1].transform.childCount)
                {
                    Transform child = cells[j + 1].transform.GetChild(0);
                    child.SetParent(cells[j].transform);
                    //GameObject obj = NGUITools.AddChild(cells[j], cells[j + 1].transform.GetChild(0));
                    child.localPosition = Vector3.zero;
                }
            }
        }
 
  
 
 

猜你喜欢

转载自www.cnblogs.com/Freedom-1024/p/9378032.html