- Home /
Can't get an actual canvas size
Hi, guys!
I can't figure out how to get the actual size of a canvas. Here is the canvas in the inspector:
so you can see that its width and height are 901.2876 to 600. How can I access these values via script? When I tried several functuons, neither of them provided me a needed result. Here is the code I've used and its result:
void Awake()
{
var rect = canvas.transform as RectTransform;
Debug.Log ("sizeDelta: " + rect.sizeDelta);
// sizeDelta: 350; 233
Debug.Log ("canvas width: " + rect.rect.width + "; canvas height: " + rect.rect.height);
// canvas width: 350; canvas height: 233
Debug.Log ("scale factor: " + rect.localScale);
// scale factor: (1.0, 1.0, 1.0)
Debug.Log ("Screen size: " + Screen.width + "; " + Screen.height);
// Screen size: 350; 233
Debug.Log (Screen.currentResolution);
// 1920 x 1080 @ 60Hz
Debug.Log ("scale factor " + canvas.scaleFactor);
// scale factor 1
}
As you see, most functionl provide me the "350 : 233" size. If I divide it by the scale factor shown in inspector (see the image above), which is equal to 0.3883, I will get the correct result. But when I try to get this value by the rect.localScale functions, it provides me just a unit vector (1; 1; 1). Why? Why the scale factor is 1, when it should be 0.3883? What should I do?
Is it inheriting that scale from it's parent? If so, then the localScale would be 1, and you'd need to use the lossy scale. As long as it's scaled uniformly, that should work.
I tryed lossyScale, there is 1 either. Anyway, my canvas has no parent objects and it seems that the value indicated in the inspector should be a local parameter.
I just found the solution. The needed function is RectTransform.GetLocalCorners(). It doesn't work for a canvas, but for its children objects it works.
Answer by ctykaya · Oct 15, 2019 at 06:29 PM
Put your logic in to the start function and you will get desire result. In awake canvas scaler component doest not rendered yet so you cannot acces correct rect size.
@ctykaya This worked for me. I was putting it in an awake method and was getting undesired results. In the start function, it works fine.
public Canvas CanvasUIElement;//Set in editor
private float CanvasWidth;
private float CanvasHeight;
void Start()
{
CanvasWidth = CanvasUIElement.GetComponent<RectTransform>().rect.width;
CanvasHeight = CanvasUIElement.GetComponent<RectTransform>().rect.height;
Debug.LogFormat("Canvas width:{0} canvas height:{1} ", CanvasWidth, CanvasHeight);
}
Your answer
Follow this Question
Related Questions
Editing RectTransform scale 2 Answers
Is there a way to change UI Scale Mode without causing my UI to mess up? 1 Answer
Use the canvas scaler to resize UI on a RenderTexture's resolution ? 0 Answers
Why are the elements of my scrollview scaled different after refreshing? 0 Answers
Anchor UI elements to the root canvas 0 Answers