- Home /
Unity 5 : Best way to initialize a UI panel coming from a prefab with many text fields ?
Greetings,
I have created a panel with a list of subpanels which are ongoing games that the player may join. Each have several details (with name, description, difficulty, number of players already present, etc.). Each subpanel is coming from a prefab and dynamically created and added to the parent panel. To fill each subpanel's text field, I came with an awkward code (this is not exactly the actual code, edited for brevity) :
(
var prefabPanelGame = (GameObject)Resources.Load ("prefabs/PanelGame", typeof(GameObject));
var newPanelGame = Instantiate (prefabPanelGame, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject;
// Call to my function, see under
MyRecursiveForEachDescendantTransform
(newPanelGame, delegate(GameObject gameObject)
{
var textChild = gameObject.GetComponent<Text> ();
// test the text name for each text that has to be initialized
if (gameObject.name == "TextInformation") {
textChild.text = someText;
} else if (gameObject.name == "TextDescription") {
textChild.text = someOtherText;
etc.
});
And here is the function that visits each transform :
public void MyRecursiveForEachDescendantTransform(GameObject go, Action<GameObject> action)
{
foreach (Transform childTransform in go.transform) {
action (childTransform.gameObject);
ForEachDescendantTransform (childTransform.gameObject, action);
}
}
This code works, but I find it awkward. Plus I fear it is not optimized. Does anyone know a better way ? Thanks in advance !
Your answer

Follow this Question
Related Questions
The prefab values keep changing 0 Answers
Models/Prefabs darker in Game Mode 1 Answer
Disable on screen keyboard for mobile phones 1 Answer
binding properties to UI Text/Image etc 1 Answer
Multiple checkboxes with UI dropdown 0 Answers