Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

LocalPlayer is a nil value, how do I fix this?

Asked by 6 years ago
--drgigabyte
local soapWow = game.Players.LocalPlayer.Backpack:FindFirstChild("Soap")
function onTouch(hit)
if soapWow == true then
soapWow = nil
end
end
script.Parent.Touched:connect(onTouch)

1 answer

Log in to vote
0
Answered by
Azarth 3141 Moderation Voter Community Moderator
6 years ago

A normal script can't access LocalPlayer because it doesn't run on the client (aka you) and doesn't know who the LocalPlayer is. You can, however, get the person who touched the brick.

local players = game:GetService("Players")
function onTouch(hit)
    if hit ~= nil and hit.Parent ~= nil then
        -- Check to see if a player touched the brick
        local player = players:GetPlayerFromCharacter(hit.Parent)
        if player then 
            -- Make sure they aren't dead and they have soap
            local hum = player.Character:findFirstChild("Humanoid") 
            local backpack = player:WaitForChild("Backpack")
            local soap = backpack:findFirstChild("Soap")
            if soap and hum and hum.Health > 0 then 
                soap:Destroy()
            end
        end
    end
end

script.Parent.Touched:connect(onTouch)
Ad

Answer this question