Restoring Health Issue

Hi all.

After several months I thought I’d progressed quite nicely from a noob to ‘intermediate’ level, but it seems I’ve hit a brick wall :slight_smile:

I’m using FE to restore a player’s health to 100 when he/she picks up a pill bottle. My code works perfectly … it restores the player to full health as designed. HOWEVER, the moment I test this with two or more players, the script restores the health of ALL players. I need it to restore ONLY the player who picked-up the bottle.

Here’s my code:

Localscript:

if instance.Name == "PillBottle" then
			local ss = instance
			ss.Touched:Connect(function(plr)
				PillBottle:FireServer()
				ss:Destroy()								
			end)
		end

ServerScript:

PillBottle.OnServerEvent:Connect(function(plr)
	if not plr.Character then
    	print("waiting for character")
    	plr.CharacterAdded:wait();
    	local char = plr.Character	
	else
		local char = plr.Character
		local human = char:FindFirstChild("Humanoid")
		if (human ~= nil) then
			human.Health = human.MaxHealth
		end	
	end

Like I said, the script IS working, so I’m confident all declarations at the head of the script are fine. It’s just the ‘multi-player’ issue that’s messing with me. I have no idea why this is restoring ALL players’ health. I’m guessing it’s just something dumb and obvious that I’m not ‘getting’. Any help will be truly appreciated!!

Because the Touched event is being listened for on the client and no checks are made to see if the LocalPlayer is the user that stepped on the part, the RemoteEvent will be activated by every client whenever the part is touched. In order to resolve this, you can check if it matches the LocalPlayer or not:

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

ss.Touched:Connect(function(part)

    local player = Players:GetPlayerFromCharacter(part.Parent)

    if player == LocalPlayer then -- Alternatively, you could compare other identifying info, such as UserId
        PillBottle:FireServer() -- The RemoteEvent will only be activated if the touched event was fired from the LocalPlayer (which means that other players firing it will not activate the RemoteEvent for everyone)
        ss:Destroy()		
    end					
end)

Thank you!!! That worked perfectly … And a good, clear explanation for what was up. Makes perfect sense now. Thanks for helping me keep on learning :slight_smile:

1 Like