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

My script doesn't work when I touch the trigger, What's the problem?

-- 1 cash = 2x xp or 1 xp = 2 cash

local multi = 2

db = false

script.Parent.Touched:Connect(function(hit)
	if not db then
		db = true
		local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
		local xp = game.Players.Values.XPValue
		local Coins = plr.leaderstats.Coins

		Coins.Value = xp.Value * multi

		Coins.Changed:Connect(function()
			game.StarterGui.StatsUI.ImageLabel.CoinStat.Values.Text = Coins.Value
		end)

		multi *= 2

		wait(1)
		db = false
	end
end)

2 answers

You're changing it via StarterGui not PlayerGui, however you should consider the following:

Handle UI work on the client rather than server. Also you've got your player variable, but have not checked if it's an actual Player.

Coins.Changed:Connect(function()
	plr.PlayerGui.StatsUI.ImageLabel.CoinStat.Values.Text = Coins.Value
end)

like pwx stated in his answer, you never stated if hit.Parent actually has a player, because of that, if the hit doesn't have a player it returns nil (nothing), which can cause your script to error. also, you are meant to edit the player gui, not starter gui.

so here is a fixed version of your script:

local multi = 2

db = false

script.Parent.Touched:Connect(function(hit)
	if db then return end -- if cooldown active then the function will not do anything
	db = true
	local plr = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if plr == nil then return end -- if no player from the thing that touch it then function do nothing
	local xp = game:GetService("Players").Values.XPValue
	local coins = plr:FindFirstChild("leaderstats").Coins

	coins.Value = xp.Value * multi
	
	coins:GetPropertyChangedSignal("Value"):Connect(function()
		plr:FindFirstChild("PlayerGui").StatsUI.ImageLabel.CoinStat.Values.Text = coins.Value -- player.playergui instead of startergui
	end)
end)

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