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

Attempt to index field'Character' (a nil value)?

Getting Error

21:54:31.023 - Players.VirtuallAnomally.PlayerScripts.Punch:8: attempt to index field 'Character' (a nil value)

21:54:31.024 - Script 'Players.VirtuallAnomally.PlayerScripts.Punch', Line 8

local player = game.Players.LocalPlayer
local db = true
local Damaged = false

local Anim = Instance.new("Animation")
Anim.AnimationId = "http://www.roblox.com/asset/?id=3626253902"

game.Players.LocalPlayer.Character:WaitForChild("RightHand").Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humonoid") and not db and not Damaged and hit.Parent.Humonoid ~= game.Players.LocalPlayer.Character.Humonoid then
		if game.Players.LocalPlayer.Character.Humonoid.Health > 0 then
			Damaged = true
			game.ReplicatedStorage.Punch:FireServer(hit.Parent.Humonoid)
			
		end
	end
end)

game:GetService("UserInputService").InputBegan:Connect(function(input, event)
	if input.KeyCode == Enum.KeyCode.F and db then
		db = false
		local playAnim = game.Players.LocalPlayer.Character:WaitForChild("Humonoid"):LoadAnimation(Anim)
		playAnim:Play()
		
	-- ( V Ticks In Between Punched V ) --
		
		wait(0.5)
		
		Damaged = false
		db = true
	end
end)

Anyone Know Why this Error is Happening?

1 answer


CharacterAdded


The reason for this is probably that the character hasn't loaded in quiet yet when that line ran, therefore erroring.

To fix this, you can simply insert this line near the top of the script (after line 1 but before line 8)

local character = player.Character or player.CharacterAdded:Wait()

This will either get character outright, if it is there, or wait for it to be loaded in.


Additional bits of advice


  • I would recommend using the player variable you defined at the start, rather than spelling out game.Players.LocalPlayer everytime you want to reference the player

  • On line 10, you misspelled Humanoid as Humonoid

Hopefully this helped!

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