Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

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

This discussion is preserved as it was. New answers, comments, and votes are closed.