How to change canvas size during runtime?

I can’t seem to figure out how to change the width of a canvas during runtime. I’m using UnityEngine.UI so that shouldn’t be the problem, but I thought the Rect Transform component would be accessible automatically from a canvas object. For some context I’m trying to create an area selection box when you click and drag your mouse. The canvas is set up as a world space renderer.

Thanks in advance for your help.

You need to modify the sizeDelta property of the RectTransform. See the scripting documentation for more information.

Sorry, to clarify: I need to know how to access the RectTransform component of the canvas during runtime. From there I already know which properties of RectTransform I need to modify. For example, I thought it would be accessed using something like “canvasObject.gameObject.rectTransform” similar to how you can access the regular transform using “canvasObject.gameObject.transform”.

GetComponent();

Oh duh, thank you :slight_smile:

You can also do:
var rectTransform = gameObject.transfrom as RectTransform;

1 Like