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

Attempting to index a nil value on Backpack?

Hello, I'm completely stumped on this, I'm not the best on scripting, so forgive me for any mistakes.

This is my script:

 local GreenSaber = game.Lighting.GreenSaber:Clone()
 local player = game.Players.LocalPlayer
 local Backpack = player.Backpack
 wait(0.5)
 
 GreenSaber.Parent = Backpack
 
 end;

When I try to use it for my admin game, it comes up with the same error. Any help would be appreciated.

1 comment

0

Just so you know, if the tool is equipped, the parent of it isn't backpack.

2 answers

✓ Accepted answer

The problem is that the backpack for the player does not come up instantly like the other objects, so you have to use WaitForChild to wait for it to appear, and also if your object is nil, just check if it exists like so and also idk if your script is a localscript or a normal script, so this would not work in normal scripts

local greenSaber = game:GetService("Lighting"):FindFirstChild("GreenSaber")
local cloneSaber

if greenSaber then
	cloneSaber = greenSaber:Clone()
end

if cloneSaber then
	local player = game:GetService("Players").LocalPlayer
	local backpack = player:WaitForChild("Backpack")
	cloneSaber.Parent = backpack
end

1 comment

0

Alright, thank you.

Instances aren't loaded immediately as soon as you launc/start the game. Use WaitForChild so that it waits for the instance to be loaded before it runs the other lines.

local player = game.Players.LocalPlayer

local Backpack = player:WaitForChild("Backpack")

local GreenSaber = game.Lighting.GreenSaber:Clone()

wait(0.5) -- This wait isn't necessary.

GreenSaber.Parent = Backpack

end;

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