- Home /
 
Change Text Scale on a Canvas Child from a script.
I am trying to access a Text Child on the canvas, which I tagged "StartButton". I would like to change the scale of it from a script, which is attached to the Canvas. In that script I attempted the following:
 public Text _Text;
 public GameObject _Canvas;
 
 void Start()
 {
     _Canvas = GameObject.FindGameObjectWithTag("StartButton");
     _Text = GameObject.Find("_Canvas").GetComponent<Text>();
     _Text.text = "Test";
 }
 
               I'm still fairly new to Unity and I am working on porting a project from Gamemaker Studio. Above I was just attempting to change the text to test, but it is not finding the object. I believe I have to access the Rect Transform in order to change the scale.
I hope I explained it correctly. Any assistance would be greatly appreciated.
Thank You!
A pic would be appreciated of the hierarchy and the inspector :)
Answer by aoun111 · Mar 14, 2020 at 09:36 AM
Why using find when you can just set up the text and the canvas in the inspector?
I assume your hierarchy is --> Canvas -> Text
So, Instead of GameObject.Find("_Canvas").GetComponent(). Use GameObject.Find("_Canvas").GetComponentInChildren(). Do note that this will work correctly if only one text is a child of canvas.
Also for scale, use:
 public float scale;    // will show in inspector
 _Text.GetComponent<RectTransform>().localScale = Vector3.one * scale;
 
              Your answer