How to detect a player inside a hit function

How can I detect a player inside a script, wich uses hit function? I cannotu se LocalPlayer or fuff
function(hit, plr) because it won’t work. Get plr from character doesn’t too.
Basically I want to give a player +1 money value by detecting minerals, and then deleting them.,
My code:

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:IsA("Tool") then
		local plr = game.Players:GetPlayerFromCharacter(hit.Parent.Parent)
		local plrls = plr.leaderstats.Money.Value
		local hv = hit.Parent.SellCost
		plrls = plrls + hv.Value
		hit.Parent:Destroy()
	else
		local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
		local plrls = plr.leaderstats.Money.Value
		local hv = hit.SellCost
		plrls += hv.Value
		hit:Destroy()
	end
end)

You’re almost there, its just that not every touch will be a player, so you will need to protect against that.

script.Parent.Touched:Connect(function(hit)
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	if not plr then
		return -- this is not a player, so ignore the touch
	end

	-- your logic here
end)
2 Likes

The script runs well, but the money value isn’t applied…

plr.leaderstats.Money.Value += hv.Value

Ok now works thanks, I was a bit dumb there :sweat_smile::sweat_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.