Constant UI scale

So, i need to draw UI elements constant size. Here i have HP bars for units:
Looks fine, but in fullscreen mode it looks like this:

I drawing it via GUI.Box, converting coords with Camera.WorldToScreenPoint

I need to scale these bars proportionally with units. How can i accomplish this?

1 Like

you need to set the size of a box relative to screen size

use screen.width and screen.height set that box is always wide as 20% of screen width or how big you want it

Thanks, i already did it. But than proportions (width/height) would depend on resolution. I need to save the proportions. So i guess i need to set width to % of the screen and height to % of the width, right?

P.S. I found that my old method works incorrectly only in “maximize” option in the editor. But works just fine with all resolutions of the build. Is that a bug?

width should be set to % of screen.width and height to % of screen.height.
This way box will stay the same size proportional to screen. if you resize screen to be 200% of original size box will be also 200% original size.
if that is what you asked?

or maybe new ui image fill instead of old gui box?
http://docs.unity3d.com/Manual/script-Image.html
http://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html

Thanks! Looks like this now:

        public static GameObject CreateRect(Vector2 position, Vector2 size, Color color) {
            Texture2D texture = new Texture2D(1, 1);
            texture.SetPixel(0, 0, color);
            texture.Apply();
         
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, 1, 1), new Vector2(0.5F, 0.5F));
            GameObject rect = new GameObject("Rect");
            rect.transform.SetParent(canvas.transform);
            Image image = rect.AddComponent<Image>();
            image.overrideSprite = sprite;
            image.rectTransform.sizeDelta = Converter.Size2Pixels(size);

            rect.GetComponent<RectTransform>().localPosition = Converter.Size2Pixels(position);

            return rect;
        }

P.S. This problem with “maximized game view” in editor appears even if i set width in % of screen width. In other words if i draw UI element 10% of screen wide, it will be 10% of the screen in game view and in all resolutions in the build. But it will not be 10% of screen in editor if i check “maximize on play”. By the way im using Unity 5.1.1f1.