using
m_nameText = GameObject.Find( “Canvas” ).AddComponent();
in a loop to create several Text objects I then have :
Can’t add ‘Text’ to Canvas because a ‘Text’ is already added to the game object!
well i create now a gameobject for each ui.text, but i don’t see how to let that gameobject becoming the child of the canvas :
m_oTextObject.transform.parent = GameObject.Find( “Canvas” ).transform;
doesn’t set the canvas as parent of the gameobject embedding the ui.text
could you post your whole creating loop?
can’t paste the whole code soz
class Container
{
private GameObject m_oTextObject;
public Text m_nameText;
public Container( string ai_sDescription )
{
m_oTextObject = new GameObject();
m_oTextObject.transform.parent = GameObject.Find( “Canvas” ).transform;
m_nameText = m_oTextObject.AddComponent< Text >();
m_nameText.text = ai_sDescription;
}
}
hmm looks like it’d be fine to me,
Try creating a reference to the canvas as a public var and assign it in the inspector (GameObject.Find is a slow operation) this might also solve you issue maybe.
Also use transform.SetParent(go) since if you use parent it will cause problems with reference res
i still fail to get the display of the text
concretely would it be possible to have some code sample of how to dynamically create and display a ui.text ?
ok with that code :
m_testTextObject = new GameObject();
m_testTextObject.transform.SetParent( GameObject.Find( “Canvas” ).transform );
m_testText = m_testTextObject.AddComponent< Text >();
m_testText.name = ai_sName + " name";
m_testText.font = ai_oFont;
m_testText.text = ai_sDescription;
I’m using this solution for creating dynamically Text elements within a Canvas:
a) Create your desired Text UI object with all it’s properties in the editor and assign it to the canvas.
b) Now hide the Text object by disabling it in the editor- it’s used as a template for all other instances.
c) You need the Reference of the canvas (e.g. rootCanvas) and the Text UI template object (e.g. textTemplate)
d) Now i’m using this pseudo code to create new instances
Component newTextInstance = MonoBehaviour.Instantiate(textTemplate, new Vector3(…), Quaternion.identity) as Component;
newTextInstance .transform.SetParent(rootCanvas.transform);
newTextInstance .gameObject.SetActive(true);