Less if in this script

Have a way to have less if in this script?

local xp = game.Players.LocalPlayer.Xp.Value
local xpRequired = game.Players.LocalPlayer.XpRequired.Value
local xpBar = script.Parent.XpBar
local plrGui = game.Players.LocalPlayer.PlayerGui
if xp >= math.floor(XpRequired/100 *1) then --if xp is in between 1% and 2% of required
plrGui.ScreenGui.Frame.UIGridLayout.CellSize = UDim2.new(0,6,0,50) --0,6 = 1% of xpBar
end
if xp >= math.floor(XpRequired/100 *2) then --if xp is in between 2% and 3% of required
plrGui.ScreenGui.Frame.UIGridLayout.CellSize = UDim2.new(0,12,0,50) --0,12 = 2% of xpBar
end
if xp >= math.floor(XpRequired/100 *3) then --if xp is in between 3% and 4% of required
plrGui.ScreenGui.Frame.UIGridLayout.CellSize = UDim2.new(0,18,0,50) --0,18 = 3% of xpBar
end

and continues until XpRequired/100*100

Are you asking how you can make this code more efficient?

yeah, less “if”, more organized

…

Usually people only store code in variables and all to make the process of writing the script easier, but if you already have the entire script written out and it isn’t a 1000 lines long; I don’t see why you would need to do so. So far it looks fine to me, the only thing that could be changed would be that you should use the PlayerGui and not StarterGui. The StarterGui’s children gets cloned into the PlayerGui’s children. So you should use game.Players.LocalPlayer.PlayerGui.Frame instead.

i dont have the entire script written out (1000 lines long), i’m searching a easier way, more organized, if no way, i’m gonna write the entire script (1000 lines) , and i know that its playergui

A more practical approach would be to do this:

local p = (xp / xpRequired) * 600
expBar.Size = UDim2.new(0, p, 0, 50)

I’m assuming your expBar is 600 pixels because I just did the math for it. Also, you’re updating the ui in StarterGui, which won’t do anything – what the player sees on their screen as a ui element is a descendant of their PlayerGui, which can be obtained using:

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

And to point out, if this isn’t in an event or loop (shouldn’t use a loop for this anyways), the if statements will only run once. Also, the values for the xp and xpNeeded are kept constant, but these are if they aren’t in an event. Consider the changed event.

All together, your code should be:

local Player = game.Players.LocalPlayer
local PlayerGui = Player:WaitForChild("PlayerGui")
local xp = Player:WaitForChild("Xp")
local xpRequired = Player:WaitForChild("XpNeeded")

function update()
    local p = (xp.Value / xpNeeded.Value) * 600
    PlayerGui.ScreenGui.Frame.UIGridLayout.CellSize = UDim2.new(0, p, 0, 50)
end

xp.Changed:Connect(update)
3 Likes

thank you so much, you helped me very much <3