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

Adding coins to a leaderstat when touching a brick?

I have been experimenting for a while and the closest i can get to is

function onTouched(part) 
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	-- Display an 'IntValue' on leaderboard
	local Coins = Instance.new("IntValue")
	Coins.Name = "Coins"
	Coins.Value = Coins.Value + 200
	Coins.Parent = leaderstats
end

Any ideas on what was done wrong?

2 answers

✓ Accepted answer

You almost got it right! But there is 1-2 problems stopping you from completing your ask, let me help you out.

local function onTouched(part)
	if part.Parent:FindFirstChildOf('Humanoid') then -- first check if it's a potential player
		local player = game.Players:GetPlayerFromCharacter(part.Parent) -- see if its a player
		if player then -- final check
			
			if Player:FindFirstChild('leaderstats') == nil then -- check if player already has leaderstats or not
			local leaderstats = Instance.new('Folder', player) -- you forgot to parent it
			leaderstats.Name = 'leaderstats'
			local Coins = Instance.new('IntValue', leaderstats)
	   		Coins.Name = "Coins"
			Coins.Value = 0 -- default value at start
			end
			
			if player:FindFirstChild('leaderstats') ~= nil then -- check if player now has leaderstats		player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 200 -- give them 200 coins

			end


		end
	end
end

Though ABritishChap's answer is correct, theres a way to make it simpler.

Heres how:

local function onTouched(part)
	local plr = game.Players:GetPlayerFromCharacter(part.Parent)
	if plr then -- If its a player
		if not plr:FindFirstChild("leaderstat") then -- Check if player already has leaderstats or not
			local leaderstats = Instance.new("Folder", plr) -- Create leaderstats then parent it to the player
			leaderstats.Name = "leaderstats"
			local Coins = Instance.new("IntValue", leaderstats)
			Coins.Name = "Coins"
			Coins.Value = 0 -- Default value at start
		end
		if plr:FindFirstChild("leaderstats") ~= nil then -- Check if player now has leaderstats      
			plr.leaderstats.Coins.Value = plr.leaderstats.Coins.Value + 200 -- Give them 200 coins
		end
	end
end

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