Changing GUI Text from a .Touched Function

I am just getting back into scripting and I am having a very hard time getting this function to change GUI text. It changes the text if I place it outside of a function, however it will not change inside the function. Here’s my code.

local Coin = script.Parent
local Balance = 0
local debounce = false
local CoinCount = game.StarterGui.ScreenGui.TextLabel


Coin.Touched:Connect(function(hit)
	if debounce == false then
		debounce = true
		Balance += 1
		CoinCount.Text = "Coins: " .. Balance
		Coin.Position = Vector3.new(math.random(14, 65), 3, math.random(-44.5, -11))
		wait(.5)
		debounce = false
	end
end)
1 Like

You should change the text inside PlayerGui instead of StarterGui.

1 Like

What do you mean? I don’t see PlayerGui.

local Players = game:GetService("Players")

local CoinCount = Players.LocalPlayer.PlayerGui.ScreenGui.TextLabel
1 Like

its better to fire a remote event to the client in here

local Coin = script.Parent
local Balance = 0
local debounce = false



Coin.Touched:Connect(function(hit)
	if debounce == false then
		debounce = true
		Balance += 1	
       game.ReplicatedStorage.Remote:FireClient(game.Players:GetPlayerFromCharacter(hit.Parent))
       Coin.Position = Vector3.new(math.random(14, 65), 3, math.random(-44.5, -11))
wait(.5)
debounce = false
end
end)

local script

local Player = game.Players.LocalPlayer
game.ReplicatedStorage.Remote.OnClientEvent:Connect(function()
local CoinCount = player.PlayerGui.ScreenGui.TextLabel
CoinCount.Text = "Coins: " .. Balance
end)

since he’s using a ServerScript he wouldn’t able to use LocalPlayer.

Didn’t know it was a server script.

actually nvm, we still don’t know if its a server script or a local script
@4_crock can you tell us if its a localscript or a server script?

Incase its for server, this is how you should do it

Script (ServerScriptService)

local Players = game:GetService("Players")

local Coin = workspace.Coin
local Debounces = {}

Players.PlayerAdded:Connect(function(player)
	player:SetAttribute("Balance", 0)
end)

Players.PlayerRemoving:Connect(function(player)
	Debounces[player] = nil
end)

Coin.Touched:Connect(function(hit)
	local Player = Players:GetPlayerFromCharacter(hit.Parent)
	
	if Player and not Debounces[Player] then
		Debounces[Player] = true
		
		Coin.Position = Vector3.new(math.random(14, 65), 3, math.random(-44.5, -11))
		Player:SetAttribute("Balance", Player:GetAttribute("Balance") + 1)
		
		task.wait(0.5)
		Debounces[Player] = false
	end
end)

изображение

LocalScript (StarterGui.ScreenGui)

local Players = game:GetService("Players")

local Player = Players.LocalPlayer
local CoinCount = script.Parent:WaitForChild("CoinCount")

Player:GetAttributeChangedSignal("Balance"):Connect(function()
	CoinCount.Text = Player:GetAttribute("Balance")
end)

изображение

The coin is located in Workspace.