Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a Canvas to a specific size in world units in unity?

Assuming that I have a UI Canvas which is set to 'World Space' and positioned absolutely in the world above my cube.

My cube is resized at runtime.

Without scaling the canvas, how do I set the size of the canvas to match the known world unit width of my cube?

I know that you can set the canvas in 'canvas units' using:

var rect = canvas.GetComponent<RectTransform>();
rect.sizeDelta = new Vector2(200, 200);

However, 200x200 are canvas units, not world units; my cube is 4 units wide; what should the sizeDelta be set to?

I presume this has something to do with the CanvasScale component, but I can't figure it out; referenceUnitsPerPixel is 100, and that's completely wrong as a scale factor, and dynamicPixelsPerUnit is like 1, which is wrong too.

like image 766
Doug Avatar asked Sep 16 '25 00:09

Doug


1 Answers

You can simply do it:

  • set the Canvas component Render Mode property to World (you already did that)
  • remove the CanvasScaler component
  • your canvas is now a 3D object: set its size using RectTransform Width and Height

Please note that your Canvas will now handle very small-sized elements (the default Image size is 100x100, which will be much larger than your Canvas).

Hope this helps,

like image 176
Kardux Avatar answered Sep 17 '25 19:09

Kardux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!