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

How would you fix attempt to index nil with 'WaitForChild'?

Asked by 3 years ago
Edited by Amiaa16 3 years ago

I was scripting a gun for my game and had this problem when I tried to locate the Humanoid of the character. I kept getting this error attempt to index nil with 'WaitForChild' Im using a local script to execute this.

local gun = script.Parent

local player = game.Players.LocalPlayer

local character = player.Character

local humanoid = character:WaitForChild("Humanoid")
repeat wait() until character:WaitForChild("Humanoid")


local animation = Instance.new("Animation")

animation.Name = "Shoot"

animation.Parent = script.Parent



animation.AnimationId = "http://www.roblox.com/asset/?id=6682923631"

local animtrack = humanoid:LoadAnimation(animation)


local gun_shot = gun.Handle['Gun Shot']


local ReplicatedStorage = game:GetService('ReplicatedStorage')

local remoteEvent = ReplicatedStorage:WaitForChild('ShotEvent')

local shooting = false

local equipped = false

local mouse = player:GetMouse()

local mouseConnection


gun.Equipped:Connect(function()



    equipped = true



    mouse.Icon = 'rbxassetid://117431027'



    mouseConnection = mouse.Button1Down:Connect(function()

        shooting = true

        while shooting and equipped do

            remoteEvent:FireServer(gun.Handle.Position, gun.Handle.Orientation, mouse.Hit.p)
            animtrack:Play()
            gun_shot:Play()

            mouse.Button1Up:Connect(function()
                animtrack:Stop()
                shooting = false

            end)

            wait(0.1)

        end

    end)

end)


gun.Unequipped:Connect(function()

    equipped = false

    mouseConnection:Disconnect()

end)

1 answer

Log in to vote
0
Answered by 3 years ago

You are doing this but just incase try it because it is what I use when the character is nil

local Character = game.Players.LocalPlayer.Character
if not Character or not Character.Parent then
    Character = game.Players.LocalPlayer.CharacterAdded:Wait()
end
Ad

Answer this question