✓ Accepted answer
Yes, the character is nil since it is not loaded yet. Similarly though, when a player dies, that Player.Character variable will reference to that old character. That's why sometimes people have this problem "I respawned and script isn't working" kind of thing since you are using the old character (which is destroyed on death).
You should hold your script until the character is added by doing this:
local tool = script.Parent
local updateMagic = game.ReplicatedStorage:WaitForChild("RemoteEvents").UpdateMagic
local backpack = tool.Parent
local player = backpack.Parent
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:FindFirstChild("Humanoid")
The thing I added here is an event, which is for the player when the character loads in. You can also pause the script until the event happens using the :Wait() function on the event itself.
The process is, if there is no player.Character (which is nil) then wait till the character is added.
I mentioned before that referencing the character might lead to referencing the older character and if you still get an error saying that the character is nil even though your holding the script till it waits then you should put this in:
local tool = script.Parent
local updateMagic = game.ReplicatedStorage:WaitForChild("RemoteEvents").UpdateMagic
local backpack = tool.Parent
local player = backpack.Parent
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:FindFirstChild("Humanoid")
player.CharacterAdded:Connect(function(NewCharacter)
character = NewCharacter
humanoid = NewCharacter
end)
You do not need a fresh copy of the player or backpack since the player is always refreshed on a new spawn and the backpack is inside of the player anyway.
You should still make a new fresh copy if you are referencing something inside of the character, such as a HumanoidRootPart.
I found some of the stuff on this devforum post:
https://devforum.roblox.com/t/localscript-in-tool-breaks-when-player-respawns/140291/2
4 comments
Is this a localscript or normal script?
local
If this is a local script you don't have to set player = backpack.Parent. You can say player = game.Players.LocalPlayer lol. You could try wait for child on some of the stuff.
attempt to index local 'character' (a nil value), same error. It was what I originally tried