Hello everyone! In my project I have a prefab of UI screen, that I should dynamically Instantiate when the game starts. This screen has large hierarchy, and somewhere deep inside the are 3 text elements. The problem is, that I need to access this text fields from my script, so I need to get them somehow. If I just searched all elements with component Text, it would not help me to differ them. Also I can search elements by name, but it seems uncorrect. What would you do?
If you have a complex object, I advise you to attach a script to the root of it, responsible for managing it and its children.
Then, you will be able to reference the desired children in the inspector of the prefab so as to have an easy access to them when you instantiate your complex object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MyComplexObject : MonoBehaviour
{
[SerializeField]
private Text firstText ; // Drag & drop the prefab's child in the inspector
[SerializeField]
private Text secondText ; // Drag & drop the prefab's child in the inspector
[SerializeField]
private Text thirdText ; // Drag & drop the prefab's child in the inspector
public Text FirstText { get { return firstText ; } } // Accessor to retrieve the text from code
public Text SecondText { get { return secondText ; } }
public Text ThirdText { get { return thirdText ; } }
}
How to use :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MyManager : MonoBehaviour
{
[SerializeField]
private MyComplexObject complexPrefab ; // Drag & drop the prefab's child in the inspector
void Start()
{
MyComplexObject instance = Instantiate( complexPrefab );
instance.FirstText.text = "Foo" ;
instance.SecondText.text = "Bar" ;
instance.ThirdText.text = "Hello world" ;
instance.GetComponent<RectTransform>().SetParent( GetComponent<RectTransform>() ) ;
}
}
Hello. I think you could attach this script to your prefab, and then, in its inspector, fill the 3 fields with the texts (not the one in the scene hierarchy, but those in your prefab’s hierarchy).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UItexts : MonoBehaviour {
public Text myText1;
public Text myText2;
public Text myText3;
// Use this for initialization
void Start () {
// initialize texts;
myText1.text = "This is my text 1";
// and so on...
}
}