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

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

Asked by 3 years ago

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)
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 CalledMetatable 0 — 3y

1 answer

Log in to vote
3
Answered by
appxritixn 2235 Moderation Voter Community Moderator
3 years ago

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

Ad

Answer this question