【Unity3D】【NGUI】grid下面的item的重複利用
阿新 • • 發佈:2019-02-07
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 UITools { /* usage: List<GameObject> canUseList = UITools.GetCanUseItemList(gridRoot); for (int i=0; i<totalData.Length; ++i) { GameObject go = UITools.GetNewItemObj(canUseList, gridRoot, prefab); // do init } UITools.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.SetActiveSelf (go, true); return go; } static public T GetNewItemObj<T> (List<T> canUseList, GameObject root, GameObject prefab) where T : Component { T item = null; if (canUseList.Count > 0) { item = canUseList [0]; canUseList.RemoveAt (0); } else { item = NGUITools.AddChild (root, prefab).GetComponent<T>(); } item.name = string.Format("{0:D3}", 0); NGUITools.SetActiveSelf (item.gameObject, true); return item; } 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.SetActiveSelf (item, false); } } static public void UnActiveUnuseItem<T> (List<T> canUseList) where T : Component { foreach (var item in canUseList) { NGUITools.SetActiveSelf (item.gameObject, false); } } static private bool IsNotTemplateGameObject(GameObject go) { bool result = !go.name.ToLower().Contains("template_"); if (!result && go.activeSelf) { NGUITools.SetActiveSelf(go, false); } return result; } }