Search code examples
luaroblox

Attempt to index nil with FindFirstChild


Script:

local ToolFolder = game:GetService("ServerStorage"):FindFirstChild("SavedItems")
local DataStoreService = game:GetService("DataStoreService")
local SaveData = DataStoreService:GetDataStore("SaveData")

game.Players.PlayerAdded:Connect(function(player)
    local ToolData = SaveData:GetAsync(player.UserId)
    local BackPack = player:WaitForChild("Backpack")
    local StarterGear = player:WaitForChild("StarterGear")

    if ToolData ~= nil then
        for i, v in pairs(ToolData) do
            if ToolFolder:FindFirstChild(v) and BackPack:FindFirstChild(v) == nil      and StarterGear:FindFirstChild(v) == nil then
                ToolFolder[v]:Clone().Parent = BackPack
                ToolFolder[v]:Clone().Parent = StarterGear
            end
        end
    end

    player.CharacterRemoving:Connect(function(Character)
        Character:WaitForChild("Humanoid"):UnequipTools()
    end)
end)

game.Players.PlayerRemoving:Connect(function(player)
    local ToolTable = {}

    for i,v in pairs(player.Backpack:GetChildren()) do
        table.insert(ToolTable, v.Name)
    end
    if ToolTable ~= nil then
        SaveData:SetAsync(player.UserId, ToolTable)
    end
end)

Issue:

ServerScriptService.SaveTools:12: attempt to index nil with 'FindFirstChild'

Couldn't find a solution. Appreciate any help. :)


Solution

  • Any time you see "attempt to index nil with x" you need to look at where you are asking for "x" and realize that the object holding "x" doesn't exist. The job then becomes figuring out why that object doesn't exist.

    In your case, whatever object that you are calling "FindFirstChild" on line 12 doesn't exist. Sadly, line 12 uses this three times :

    if ToolFolder:FindFirstChild(v) and
       BackPack:FindFirstChild(v) == nil and
       StarterGear:FindFirstChild(v) == nil then
    

    So let's look at where ToolFolder, BackPack, and StarterGear were created and see if that gives any clues.

    local ToolFolder = game:GetService("ServerStorage"):FindFirstChild("SavedItems")
    ...
    local BackPack = player:WaitForChild("Backpack")
    local StarterGear = player:WaitForChild("StarterGear")
    

    Backpack and StarterGear looks correct, they are both children of the Player, and both look to be spelled correctly.

    ToolFolder is probably the culprit, you should make sure there is actually an object named SavedItems in ServerStorage. Double check that the spelling and capitalization are correct.