Hello,
I'm trying to instantiate a prefab multiple times and then add those instances to a grid. This seems to work just fine through the use of GameObject newItem = NGUITools.AddChild(itemsGrid.gameObject, prefabItem); but the parent draggable panel of itemGrid doesn't clip the new children. I've searched the forum and have seen it mentioned that the prefab should probably not have it's own panel, but every time I add a label or button or any NGUI object it automatically adds a panel to my prefab. Could someone please point out where I'm making the mistake? Here's my layout:
+ ItemPrefab (DragPanelContents linked to ItemsDraggablePanel)
+ -- NameLabel
+ -- StatusSprite
+ -- ImageButton
+ ItemsDraggablePanel (Hard Clip)
+ -- ItemsGrid
The section of code that makes new items and adds them to the grid is:
private void OnGetItemssSuccess(List<Item> items)
{
if( itemPrefab == null )
{
Debug.LogError("Could not find ItemPrefab!");//linked through Unity magic
return;
}
foreach (Item item in items)
{
GameObject newItem = NGUITools.AddChild(itemsGrid.gameObject, itemPrefab);
UILabel[] labels = newItem.GetComponentsInChildren<UILabel>();
foreach (UILabel label in labels)
{
switch (label.name)
{
case "ItemLbl":
label.text = item.name;
break;
case "LevelLbl":
label.text = item.level;
break;
default:
break;
}
}
isOnline = item.online == 1;
UISprite[] sprites = newItem.GetComponentsInChildren<UISprite>();
foreach (UISprite sprite in sprites)
{
switch (sprite.name)
{
case "ItemSprite"://for future use
break;
case "StatusSprite":
sprite.name = (isOnline) ? "PSPS_StatusLight_Green" : "PSPS_StatusLight_Red";
break;
default:
break;
}
}
itemsGrid.Reposition();
itemsDraggablePanel.ResetPosition();
}
}
Okay, so here's the solution! The prefab that's being instantiated cannot have a panel, but NGUI objects need one and will add it automatically if one doesn't exist in one of their parents. The trick is to add a game object with a panel as a parent to the prefab and then remove the panel from the prefab:
+ ItemPrefabParent (UIPanel)
+ -- +ItemPrefab (DragPanelContents only) (call NGUITools.AddChild on this!)
+ + -- NameLabel
+ + -- StatusSprite
+ + -- ImageButton