How to make it so only the player can touch the part

Hello all, so I made a script which is “Money” and when u touch its gives you money for touching it but literally anything can touch it in the game and it will delete

  • Source Code
script.Parent.Touched:Connect(function(plr)
	local name = plr.Parent.Name
	local playerInstance = game:GetService("Players")
	local player = playerInstance:WaitForChild(name)
	
	player.leaderstats.Cash.Value = player.leaderstats.Cash.Value + 5
end)

Also forgot to mention, there’s actually a dummy model that drops the cash because once u clicks it , it “poops” out money
image

1 Like

the problem is that this is touching things other than players and you should be using :GetPlayerFromCharacter to see if it is a player.

script.Parent.Touched:Connect(function(hit)
	local plr = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)

	if plr then
		plr.leaderstats.Cash.Value = player.leaderstats.Cash.Value + 5
	end
end)
1 Like

This should work:

script.Parent.Touched:Connect(function(part)
	if part.Parent:FindFirstChild("Humanoid") and game:GetService("Players"):FindFirstChild(part.Parent.Name) then
		local name = plr.Parent.Name
		local playerInstance = game:GetService("Players")
		local player = playerInstance:WaitForChild(name)
		player.leaderstats.Cash.Value = player.leaderstats.Cash.Value + 5
	end
end)
1 Like

Assuming the script works when you touch it, I would use

game:GetService("Players"):GetPlayerFromCharacter(plr.Parent)
if player then

    --insert money award code here

end
1 Like

This also works Aswell. just the other one was a little easier

Also the dummy in the workspace has a humanoid so it would allow it to touch it

It also checks if they are a player, but yeah the other solution is much simpler

OH, I didn’t see that but thanks for the support, everyone

2 Likes