UI AutoScaler [RichText compatibility]

Hello!

Recently, ROBLOX has added RichText and, as of now, there is no support for scaling these brand new UI elements.
I have worked around a solution which is far more reliable to work on scaling all UI elements contained in a ScreenGui, including RichText TextLabels.

CODE

local PlayerService = game:GetService("Players")
local playerScreen = PlayerService.LocalPlayer:WaitForChild("PlayerGui")

--Chose ideal monitor dimensions
local x = 1920
local y = 1080
local baseScale = (x*x + y*y)^(1/2)

--Actual variable that changes when the screen size changes
local scale = 1

--Updates the scale variable and all the ScreenGui's in 'updaters'
local updaters = {}
local currentCamera = workspace.CurrentCamera
local function updateScale()
    scale = currentCamera.ViewportSize.Magnitude/baseScale
    for screen, update in next, updaters do
        update()
    end
end

--Connect an updater for when the screen size changes
currentCamera:GetPropertyChangedSignal("ViewportSize"):Connect(updateScale)

--First update...
updateScale()

--Get ScreenGui's in the game and allocate their respective update functions in 'updaters'
local function addAutoScale(screen)
    local constraint = Instance.new("UIScale")
    constraint.Scale = scale
    constraint.Parent = screen
    
    --Stop updating this ScreenGui
    screen:GetPropertyChangedSignal("Parent"):Connect(function()
        if not screen:IsDescendantOf(game) then
            updaters[screen] = nil
        end
    end)
    
    local function update()
        constraint.Scale = scale
    end
    
    updaters[screen] = update
end

playerScreen.ChildAdded:Connect(function(child)
    if child.ClassName == "ScreenGui" then
        addAutoScale(child)
    end
end)

for i, screen in next, playerScreen:GetChildren() do
    if screen.ClassName == "ScreenGui" then
        addAutoScale(screen)
    end
end

HOW TO USE

  1. Create a LocalScript inside ReplicatedFirst.
  2. Paste the code mentioned above inside it.
  3. Enjoy.

The awesome thing about this code is that you can specify an ideal monitor size and it will try to scale any UI element to properly fit the expected monitor’s size.

KNOWN PROBLEMS

  1. ‘Pixels’ will get rounded to the lowest integer if the UI element’s width or height has a decimal part. For instance, UDim2.new(0, 205.4, 0, 100.2) will be rounded to UDim2.new(0, 205, 0, 100). This can be an issue for many developers, but I think it will always have a small error if the monitors are not identical to the ideal monitor you are aiming for.

Best regards,
Octonions

18 Likes

Glad to see this spawning into existence! I’ll be sure to take a look and possibly use this! :slight_smile:

2 Likes

Wouldn’t PlayerGui be a child of the local player not the player service?

2 Likes

Hey, @Narunzo.

Yes!
Thanks for pointing that out. I have fixed the mistake.

Best regards,
Octonions

2 Likes