Search code examples
luaroblox

attempt to index nil with 'WaitForChild'


I am currently making a script so that when a block is touched, the player will go to position. It is

game.Workspace.AUPortal.Glitch4.Position

and me need help in this error.

Workspace.A12.MovePlayer:4: attempt to index nil with 'WaitForChild'

Script:

function onTouched(hit)
    local h = hit.Parent:findFirstChild("Humanoid")
    local playerMod = require(game:GetService("Players").LocalPlayer:WaitForChild("PlayerModule"))
    local controls = playerMod:GetControls()
    if h~=nil then
        controls:Disable()
        pos = game.Workspace.AUPortal.Glitch4.Position 
        h:MoveTo(pos)
        wait()
    end
end

script.Parent.Touched:connect(onTouched)

Solution

  • I can only assume you are trying to access the LocalPlayer inside of a standard Script which is something you cannot do.

    You can only access the LocalPlayer inside of a LocalScript, hence why you're getting an error for the WaitForChild. Because the LocalPlayer does not exist (it's nil).

    With the Touched event you can get actually get a reference to the player you're trying use:

    Part.Touched:Connect(function(HitPart)
     local Humanoid = HitPart.Parent:FindFirstChild('Humanoid');
     if (Humanoid) then
      local Player = game.Players:GetPlayerFromCharacter(HitPart.Parent);
      -- You can then use this player reference.
     end
    end)