NGUI讨论群:333417608
使用grid放置item的时候,每次数据可能都不一样,但是每次都删除grid下面的节点,之后动态创建新的item是比较浪费的。
写个简单的工具函数,原理很简单。
1、先获得grid下面的可用item
2、根据data的大小进行初始化
3、每次在可用的item列表里面获取新的item,如果不够用了,就创建新的item
4、disable掉没用的item
附:每个grid下面预先要有一个名字包含“Template_”的模板item。这个模板不会被用,之前尝试过把这个模板也当做一个item正常使用,但是有些NGUI的widget会出现BUG。
using UnityEngine;
using System.Collections.Generic;
// qq group : 333417608
//
public class SZUITools
{
/* usage:
List<GameObject> canUseList = SZUITools.GetCanUseItemList(gridRoot);
for (int i=0; i<totalData.Length; ++i)
{
GameObject go = SZUITools.GetNewItemObj(canUseList, gridRoot, prefab);
// do init
}
SZUITools.UnActiveUnuseItem(canUseList);
// prefab is the template
*/
static public GameObject GetNewItemObj (List<GameObject> canUseList, GameObject root, GameObject prefab)
{
GameObject go = null;
if (canUseList.Count > 0) {
go = canUseList [0];
canUseList.RemoveAt (0);
} else {
go = NGUITools.AddChild (root, prefab);
}
NGUITools.SetActive (go, true);
return go;
}
static public T GetNewItemObj<T> (List<GameObject> canUseList, GameObject root, GameObject prefab) where T : Component
{
GameObject go = GetNewItemObj(canUseList, root, prefab);
return go.GetComponent<T> ();
}
static public List<GameObject> GetCanUseItemList (GameObject root)
{
List<GameObject> itemList = new List<GameObject> ();
Transform rootT = root.transform;
for (int i=0; i<rootT.childCount; ++i) {
GameObject go = rootT.GetChild (i).gameObject;
if (IsNotTemplateGameObject(go))
{
itemList.Add (go);
}
}
return itemList;
}
static public List<T> GetCanUseItemList<T> (GameObject root) where T : Component
{
List<T> childrenList = new List<T> ();
Transform rootT = root.transform;
for (int i=0; i<rootT.childCount; ++i) {
Transform child = rootT.GetChild (i);
T t = child.GetComponent<T> ();
if (t != null && IsNotTemplateGameObject(child.gameObject)) {
childrenList.Add (t);
}
}
return childrenList;
}
static public void UnActiveUnuseItem (List<GameObject> canUseList)
{
foreach (var item in canUseList) {
NGUITools.SetActive (item, false);
}
}
static private bool IsNotTemplateGameObject(GameObject go)
{
bool result = !go.name.ToLower().Contains("Template_");
if (!result && go.activeSelf)
{
NGUITools.SetActive(go, false);
}
return result;
}
}
【Unity3D】【NGUI】grid下面的item的重复利用,布布扣,bubuko.com
【Unity3D】【NGUI】grid下面的item的重复利用
原文:http://blog.csdn.net/u012091672/article/details/21159075