Text does not change when clicking button in UI

Hello, I’ve been trying to make a function that changes the text inside a button, but for some reason it doesn’t seem to work even tho it doesn’t errors in the console, I’ve tried many ways to do it but it still doesn’t changes.

local function changeNumber(text)
	if text == "0" then
		text = "1"
	elseif text == "1" then
		text = "2"
	elseif text == "2" then
		text = "3"
	elseif text == "3" then
		text = "4"
	elseif text == "4" then
		text = "0"
	end
end

script.Parent.Input1.MouseButton1Click:Connect(function()
	local Number = script.Parent.Input1.Number.Text
	ButtonSelect:Play()
	changeNumber(Number)
end)
1 Like

You never actually change the text. From what I assume, the Number variable is the text. It’d be better if you defined the actual TextBox/ Frame/ etc and then changed the text later. Confusing? Just look at the code below and it should work.

local function changeNumber(text)
	if text == "0" then
		text = "1"
	elseif text == "1" then
		text = "2"
	elseif text == "2" then
		text = "3"
	elseif text == "3" then
		text = "4"
	elseif text == "4" then
		text = "0"
	end
  
    return text
end

script.Parent.Input1.MouseButton1Click:Connect(function()
	local Number = script.Parent.Input1.Number
	ButtonSelect:Play()
	Number.Text = changeNumber(Number.Text)
end)

PS: I forgot to mention it, but you also need to return the new text value, as currently it’s just changing it’s variable called “text” to whatever you set it as and then leaving it at that.

1 Like

It finally worked, thank you so much!

Adding on to the solution, instead of having a bunch of if checks which is really inefficient, you can use modulo.

function changeNumber(text: string): string
    return tostring((tonumber(text)+1)%5)
end

print(changeNumber("1")) -- "2"
print(changeNumber("3")) -- "4"
print(changeNumber("4")) -- "0"
1 Like