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

Touched function not working and doing what its supposed to do?

When I touch the part, it does nothing and I don't know why.

Here is the script:

local MarketplaceService = game:GetService("MarketplaceService")
local gamepassId = 16463231

script.Parent.Touched:Connect(function(player)
	if MarketplaceService:UserOwnsGamePassAsync(player.UserId, gamepassId) then
		-- Double Coins
		player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 16
	else
		player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 8
	end

	player.Character.Humanoid.MaxHealth = 0 -- Respawn player after they collect their cash
end)

1 answer

Are you using a local script in the workspace? Local scripts don't run in the workspace and you need to use a normal script.

Also the .Touched event returns the part that got touched like the player's arm or leg so you need to get the parent of that part and see if you are able to get a player from the character first, so your code should something like this:

local Players = game:GetService("Players")
local MarketplaceService = game:GetService("MarketplaceService")
local gamepassId = 16463231

script.parent.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent) -- the parent of the touched part is expected to be a character
	if player == nil then
		print("Didn't touch a player")
		return
	end
	
	-- Your code here
    	if MarketplaceService:UserOwnsGamePassAsync(player.UserId, gamepassId) then
        	-- Double Coins
        	player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 16
    	else
        	player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 8
    	end

	player.Character.Humanoid.Health = 0 -- You should use Humanoid.Health not Humanoid.MaxHealth
end)

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