NGUI ScrollView动态加入和删除对象。

动态加入,基本思想是:

1、先把要加入的元素在编辑器中编辑好,制作成一个prefab。

2、在代码中,动态的生成一个新的对象增加到Grid对象的子对象中。这里利用到了Resources对象,这个对象的使用方法能够參照官网,就是在Assets文件夹下有一个Resources文件夹,位置随便,仅仅要是在Assets文件夹下即可。

3、加入对象之后,能够从这些对象中获取子对象进行属性的改动,比方加入了十个武器,那么十个武器的Icon,名字和价格都不一样。


以下代码代码中:


代码例如以下:

                           var GameObject  ngui_grid = GameObject.Find ("UIGrid");
            UIGrid ngui_ui_grid = ngui_grid.GetComponent<UIGrid>();

            GameObject _gridItem = NGUITools.AddChild(ngui_grid, (GameObject)(Resources.Load("GridItemPrefab")));
            // 生成的对象又一次命名

            _gridItem.name = "gridItem" + indexSlot;


            var item = itemManage.Items[itemslot.Index];
            

            // 动态改变每个武器对象的显示属性。
            Transform[] allChildren = _gridItem.GetComponentsInChildren<Transform>();
            foreach (Transform child in allChildren)
            {
                if(child.gameObject.tag == "GridItemIcon")
                {
                    UISprite _ItemIcon = child.gameObject.GetComponent<UISprite>();
                    _ItemIcon.spriteName = item.Icon.name;
                }
                else if(child.gameObject.tag == "GridItemName")
                {
                    UILabel _ItemName = child.gameObject.GetComponent<UILabel>();
                    _ItemName.text = item.Name+" "+itemslot.Index;
                }
                else if(child.gameObject.tag == "GridItemPrice")
                {
                    UILabel _ItemPrice = child.gameObject.GetComponent<UILabel>();
                    _ItemPrice.text = item.Price+"$";
                }
                else
                {
                    // do nothing,,,
                }
            }

            // 加入这个标志,能够让元素加入之后,Grid对元素进行又一次排列,
            ngui_ui_grid.repositionNow = true;

            return;



元素删除,代码例如以下:

            for(int k = 0;k<ngui_grid.transform.childCount;k++)
            {
                GameObject go = ngui_grid.transform.GetChild(k).gameObject;
                Destroy(go);
                

                // 这个标记会让元素马上又一次排列。
                ngui_ui_grid.Reposition();
            }




原文地址:https://www.cnblogs.com/mengfanrong/p/4318997.html