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

attempted to index nil with 'Character' error how to fix?

I tried creating a bread tool that when clicked, it would heal the player by 25 health. I did this all in a ServerScript, I don't know if I need to use a LocalScript.

My Code:

local bread = script.Parent
local breadHandle = bread.Handle

function onClick(player)
	if player.Character.Humanoid.Health > 100 then
		player.Character.Humanoid.Health = player.Character.Humanoid.Health + 25
		breadHandle.Yummy:Play()
		wait(1)
		bread:Destroy()
	else
		local msg = Instance.new("Message")
		msg.Parent = workspace
		msg.Name = "Msg"
		msg.Text = "You are already at max health! Get damaged then use the bread."
	end
end
bread.Activated:Connect(onClick)

1 comment

0

One. Dont use Message wtf, Two. Use bread.Activated:Connect(function(player) instead of function onClick(). Three. to get the player use FindFirstAncestor() You need to

1 answer

✓ Accepted answer

Tool.Activated does not provide a player argument, which is why player is nil.

As it looks like your script is a child of the tool, you could use a local script and a server script.

Inside the ServerScript you would adjust the player's health. Inside the LocalScript, you would handle the Activated event and fire a remote event to the ServerScript.

ServerScript

local Event = -- Location of remote event
Event.OnServerEvent:Connect(function(player,bread)
	if player.Character.Humanoid.Health < 100 then
		local breadHandle = bread.Handle
		player.Character.Humanoid.Health = player.Character.Humanoid.Health + 25
		local LoadedYummy = player.Character.Humanoid:LoadAnimation(breadHandle.Yummy)
		LoadedYummy:Play()
		wait(1)
		bread:Destroy()
	end
end)

LocalScript

local bread = script.Parent
local breadHandle = bread:WaitForChild("Handle",10)
local player = game.Players.LocalPlayer

local Event = -- Location of remote event

bread.Activated:Connect(function()
	if player.Character.Humanoid.Health >= 100 then
		local msg = Instance.new("Message") -- Should not be used, see my comment at the end of this answer
		msg.Parent = workspace
		msg.Name = "Msg"
		msg.Text = "You are already at max health! Get damaged then use the bread."
	else
		Event:FireServer(bread)
	end
end)

A little note: Message is deprecated and should no longer be used. Instead, you should use ScreenGui and TextLabel

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