- Home /
Answer by DCTShinobi · Jan 30, 2015 at 06:30 AM
I'm not sure exactly when or how you want to display it, but this is what I've been using for my UI scripts.
Just attach a script to your canvas, and stick this in the Start() for a one time display in the console, or in your Update() for it to display every frame...
RectTransform objectRectTransform = gameObject.GetComponent<RectTransform> ();
Debug.Log("width: " + objectRectTransform.rect.width + ", height: " + objectRectTransform.rect.height);
Or you can put this into your Update() so you can get the size every time you press the spacebar...
if (Input.GetKeyDown("space"))
{
RectTransform objectRectTransform = gameObject.GetComponent<RectTransform> ();
Debug.Log("width: " + objectRectTransform.rect.width + ", height: " + objectRectTransform.rect.height);
}
Of course, this is for the width and height of the object (it works for whatever UI object you attach it to, not just a canvas). I'm not sure if it will give you the proper coordinates, though. I only work with canvases that have the Render Mode set to Screen Space - Overlay, so that's why it works for my projects.
I hope it helps! :-)
This solves my question, thanks for the answer! (Sorry I didn't accept sooner, I got pulled out of Unity work for a bit and just now made my way back)
Answer by whoopdeedoo03 · Jan 02, 2019 at 06:28 AM
You may also call RectTransform from the canvas itself...
Canvas canvas = FindObjectOfType<Canvas>();
float h = canvas.GetComponent<RectTransform>().rect.height;
float w = canvas.GetComponent<RectTransform>().rect.width;