Hello, I was making something for my game, But an error happened, Could anyone fix this?
What I was trying to do is Clone the Tools to the Player's backpack, But this error happened:
"Workspace.Lucky_Blocks.Lucky_Block1.Script: attempt to index nil with backpack"
I don't know how to fix the script.
Script:
local player = game.Players.LocalPlayer local backpack = player.Backpack local GearsFolder = game.ReplicatedStorage.Gears script.Parent.Touched:Connect(function(hit) local lucky = math.random(1,6) if lucky == 1 then GearsFolder.Bloxy_Cola:Clone().Parent = backpack elseif lucky == 2 then GearsFolder.Lightbox_Jar:Clone().Parent = backpack elseif lucky == 3 then GearsFolder.Panda_Friend:Clone().Parent = backpack elseif lucky == 4 then GearsFolder.Red_Rolling_Hoverboard:Clone().Parent = backpack elseif lucky == 5 then GearsFolder.Taco:Clone().Parent = backpack elseif lucky == 6 then GearsFolder.Toms_Beans:Clone().Parent = backpack elseif lucky > 6 then warn("Warning: Your unlucky.") end end)
Hi The problem here is that you are using a script (which is server based) to find a local player, therefore you cannot find the backpack, hence the error. So maybe try changing the script into a local script and see if you get any errors! -- PS YOU WILL NEED A REMOTE EVENT AS LOCAL SCRIPTS CANNOT DETECT TOUCHED EVENTS
Hope this helped!
Any questions? Just ask!
local GearsFolder = game.ReplicatedStorage.Gears script.Parent.Touched:Connect(function(hit) local humanoid = hit.Parent:FindFirstChild("Humanoid") local backpack = nil if humanoid then if game.Players:FindFirstChild(char.Name) then local player = game.Players:GetPlayerFromCharacter(humanoid.Parent) local backpack = player.Backpack end end local lucky = math.random(1,6) if lucky == 1 then GearsFolder.Bloxy_Cola:Clone().Parent = backpack elseif lucky == 2 then GearsFolder.Lightbox_Jar:Clone().Parent = backpack elseif lucky == 3 then GearsFolder.Panda_Friend:Clone().Parent = backpack elseif lucky == 4 then GearsFolder.Red_Rolling_Hoverboard:Clone().Parent = backpack elseif lucky == 5 then GearsFolder.Taco:Clone().Parent = backpack elseif lucky == 6 then GearsFolder.Toms_Beans:Clone().Parent = backpack elseif lucky > 6 then warn("Warning: Your unlucky.") end end)
----------EXPLANATION----------
So, I'm just gonna explain the code that I just added in.
First, there's a variable that checks if hit.Parent has a humanoid. hit.Parent is the character model.
The backpack variable is equal to nil, nil means nothingness.
After that, It checks if the character has a humanoid then, it'll run the code in that scope which is just another sanity check.
Before we go further, you'd be questioning, how is it true? "FindFirstChild just returns an instance" well if it returns something, it's true otherwise, false, or nil.
Next, it'll look through the PlayerService and see if the character name is a child of the PlayerService, I did this just in case if it's an NPC.
After that, it gets the player and the player's backpack.