Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I edit the text in a TextBox from a variable?

I'm trying to make a gun for my roblox game, and I want a GUI to give info to the player, like how much ammo is left in a clip, whether or not you're reloading etc. I am trying to get the variable "Ammo" 's value (12) into the text for the textbox, and have it decrease by 1 when it's fired. My code is:

local canFire = true

local Ammo = 12

local maxAmmo = 12

local ammoCounterText = game.StarterGui.ScreenGui.Frame.AmmoCounter.Text

script.Parent.Equipped:Connect(function(mouse)
	mouse.Button1Down:Connect(function()
		
		if canFire then
			game.ReplicatedStorage.RayCastEvent:FireServer(script.Parent.ForBullets.Position, mouse.Hit.Position)
			
				Ammo = Ammo - 1
				ammoCounterText = Ammo
				canFire = false
				wait(0.5)
				canFire = true
			end
		end
	)

	if Ammo < 1 then
	
	canFire = false
	wait(5)
	Ammo = 12
	canFire = true

	end
end)

2 answers

local ammoCounterText = game.StarterGui.ScreenGui.Frame.AmmoCounter.Text

Here, the variable is not being set to the AmmoCounter UI element, it's being set to what its text is as soon as the script starts running. Just remove the .Text on the end.

local ammoCounterText = game.StarterGui.ScreenGui.Frame.AmmoCounter

In order to modify its text, just do this:

ammoCounterText.Text = "Ammo: " .. Ammo

Also, I wouldn't keep track of how much ammo the gun is supposed to have on the client, as exploiters could easily just fire the gun an infinite amount of times. I'd create an IntValue and use it to keep track of the ammo. The server will do the subtraction. Check on the client and on the server before actually firing the gun.

4 comments

0

Where did you learn how to script?

0

I added the things you requested into my LocalScript, however when I fire the gun, nothing changes.

0

@iivSnooxy I learned by watching YouTube videos and eventually I accumulated enough knowledge to help others out.

0

@Br_eden Did you put the last code snippet in my post into the event listener?

This discussion is preserved as it was. New answers, comments, and votes are closed.