- Home /
Question by
Frunobulax · Nov 18, 2021 at 12:17 PM ·
textcanvasruntime-generation
How to add Text from script?
Hi all.
I want to add a Text from script. Is that possible?
This script leaves me with a Textcomponent on a gameObject that I can see it in the Inspector. But the text is not visible in the scene / game. Now what?
Any help is much appreciated!
Cheers
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextExperiment : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GameObject go = new GameObject("TextHolder", typeof(RectTransform));
go.transform.SetParent(this.transform);
Text myText = go.AddComponent<Text>() as Text;
myText.resizeTextForBestFit = true;
myText.fontSize = 40;
myText.GetComponent<Text>().font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
myText.text = "Hey Ma, it works!";
}
}
inspector.png
(55.2 kB)
Comment
Answer by KloverGames · Nov 18, 2021 at 01:11 PM
The text needs to be parented to the Canvas. If the text isn't on the Canvas then it will not render in the scene. I see you used some setParent code there, try to set the text onto the Canvas. Let me know if you have any other questions.
Your answer
![](https://koobas.hobune.stream/wayback/20220613045533im_/https://answers.unity.com/themes/thub/images/avi.jpg)