Tag Archives: NGUI

NGUI dynamic table contents

If you’re looking to have dynamic tables in your UI and you’re using NGUI for Unity3d, here’s how I’ve been able to do it:

In this example I have a table that contains a data driven list of available levels for a level select screen.

Create a UITable within your panel, and set the columns/padding/etc. Create a prefab to represent one of the items in your UI, and set it to a member variable of your UI script.

public GameObject AvailableLevelPrefab;

In the code that populates the table, create a reference to the table GameObject, loop over the items that you want to include in the table, and instantiate a prefab for each level.

//table game object
var levelsPanel = GameObject.Find("LevelsTable");
foreach(var level in levelsForPlanet){
 var levelUIFragment = Instantiate(AvailableLevelPrefab, levelsPanel.transform.position, levelsPanel.transform.rotation) as GameObject;

//change the level name according to how you want the table items sorted.
 levelUIFragment.name = level.SceneName;

//parent the table item to the table game object
 levelUIFragment.transform.parent = levelsPanel.transform;
 //parenting the item will change its scale. Change it back to whatever it was before
 levelUIFragment.transform.localScale = Vector3.one;
//once the table item exists, you can alter the UI elements so that they match the item. 
//in this case, I'm changing the property of a button so that when clicked, it will bring the player to the correct level
var buttonGameObject = levelUIFragment.transform.Find("Button");
 var button = buttonGameObject.GetComponent<SelectLevelButton>();
 button.PlanetName = level.SceneName;
 }

//once everything is instantiated, call the reposition method in the levels panel
 levelsPanel.GetComponent<UITable>().Reposition();

I’ve used this method a few times, and it seems to work pretty well. Anyone out there have any other methods for creating data-driven UI?

Edit: Cody just commented with an easier way to add the item to the table. Most everything stays the same, but instead of instantiating the prefab, parenting, and changing the scale, NGUI has a helper method that does all of that for you. This is how it would look:

var levelUIFragment = NGUITools.AddChild(levelsPanel, AvailableLevelPrefab);

Thanks for the tip Cody!