Attempt to index nil with "Backpack"

What I am trying to do is give a tool to every player at the beginning of a round. However, what happens is that the error in the title shows up instead. I’d love some help

local Tool = game.ServerStorage.ToolName
local function giveTool(player)
    local backpack = player:FindFirstChildOfClass("Backpack")
    if backpack then
        local tool = Tool:Clone()
        tool.Parent = backpack
    end
end

Hello Shark!
I would love to help but I need more information. Could you share the script or scripts where you are calling the function? The problem isn’t here.

Here is everything leading up to the part where it gets fired:

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local playerTable = {}
local function onPlayerDied(player)
	print(player.Name .. " has died")
	if playerTable[player.Name] then
		playerTable[player.Name]["isAlive"] = false
	end
end

local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData")
local function onPlayerAdded(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local survivals = Instance.new("IntValue")
	survivals.Name = "Survivals"
	survivals.Value = 0
	survivals.Parent = leaderstats
	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = 0
	coins.Parent = leaderstats

	-- Load player's data from the data store
	local userId = player.UserId

	-- Attempt to retrieve the player's survival data from the data store
	local success, data = pcall(function()
	return playerDataStore:GetAsync(userId)
	end)

	if success then
		if type(data) == "table" and data.survivalStats and data.coinStats then
			survivals.Value = data.survivalStats
			coins.Value = data.coinStats
		else
			survivals.Value = 0
			coins.Value = 0
		end
	else
		warn("Failed to retrieve survival data for player " .. player.Name)
	end
	end
game.Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(onPlayerDied)
Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		char:FindFirstChild("Humanoid").Died:Connect(function()
			onPlayerDied(plr)
		end)
	end)
end)
local function playerRemoving(plr)
	local success, data = pcall(function()
		local plrstats = {
			survivalStats = plr.leaderstats.Survivals.Value,
			coinStats = plr.leaderstats.Coins.Value
		}
		return playerDataStore:SetAsync(plr.UserId, plrstats)
	end)
	if not success then warn("Error while saving data: "..data) end
end
function startNewRound()
	playerTable = {}
	print("Starting")
	for _, player in ipairs(Players:GetPlayers()) do
		playerTable[player.Name] = {
			["isAlive"] = true
		}
	end
end


function endRound()
	print("Ended")
	local survivors = {} -- Table to store the remaining survivors
	for _, player in ipairs(Players:GetPlayers()) do
		if playerTable[player.Name] and playerTable[player.Name]["isAlive"] then
			table.insert(survivors, player) -- Add the player to the survivors table
			local leaderstats = player:FindFirstChild("leaderstats")
			if leaderstats then
				local survivals = leaderstats:FindFirstChild("Survivals")
				if survivals then
					survivals.Value = survivals.Value + 1
					print("Added a survival")
				end
				local coins = leaderstats:FindFirstChild("Coins")
				if coins then
					coins.Value += script.CoinsAmount.Value
				end
			end
		end
	end
	for _, survivor in ipairs(survivors) do
		local success, errorMessage = pcall(BadgeService.AwardBadge, BadgeService, survivor.UserId, script.BadgeToAward.Value)
		if not success then
			warn("Error while awarding badge:", errorMessage)
		end
	end
end
local queue = {}

Gamemodes = {
"Gamemode1" = 0.1,
"Gamemode2" = 0.1,
"Gamemode3" = 0.1
}

local queue = {}


game.Players.PlayerAdded:Connect(function(player)
	player.Chatted:Connect(function(message)
		if player.UserId == game.PrivateServerOwnerId then
			if message:sub(1, 7) == "/queue " and Gamemodes[message:sub(8)] then
				local Gamemode = message:sub(8)
				table.insert(queue, Gamemode)
				print("Gamemode '" .. Gamemode .. "' has been added to the queue.")
			end
			elseif player.UserId == game.CreatorId then
	if message:sub(1, 7) == "/queue " and Gamemodes[message:sub(8)] then
		local Gamemode = message:sub(8)
		table.insert(queue, Gamemode)
		print("Gamemode '" .. Gamemode .. "' has been added to the queue.")
	end
end

	end)
end)

function selectRandomGamemode()
	local Weight = 0
	for _, Chance in pairs(Gamemodes) do
		Weight += (Chance * 10)
	end
	local ranNumber = math.random(1, Weight)
	Weight = 0
	for Gamemode, Chance in pairs(Gamemodes) do
		Weight += (Chance * 10)
		if Weight >= ranNumber then
			return Gamemode
		end
	end
end	

function getNextGamemode()
	if next(queue) then
		local Gamemode = table.remove(queue, 1)
		ChosenGamemode = game.Lighting.Gamemode[Gamemode]
		print("The next gamemode from the queue is: "..Gamemode)
		return Gamemode
	else
		return selectRandomGamemode()
	end
end

local Tool = game:GetService("ServerStorage"):WaitForChild("Items"):WaitForChild("ToolName") -- 

local function giveTool(player)
    local backpack = player:FindFirstChildOfClass("Backpack")
    if backpack then
        local tool = Tool:Clone()
        tool.Parent = backpack
    end
end

game.Players.PlayerRemoving:Connect(playerRemoving)

local GamemodeFolder = game.ServerStorage.Gamemodes
local GamemodesToChoose = GamemodeFolder:GetChildren()
local RoundTime = script.RoundTime
local IntermissionTime = script.IntermissionTime
local IntermissonThemes = game.ServerStorage.IntermissionMusic:GetChildren()
wait(10)
local plrVotes = {}
numMapsVoting = 3

function addVote(plr:Player, mapName:string)

	plrVotes[plr] = mapName
	game.ReplicatedStorage:WaitForChild("Voted"):FireAllClients(plrVotes)
end

function removePlayerVote(plr:Player)

	plrVotes[plr] = nil
	game.ReplicatedStorage.WaitForChild("Voted"):FireAllClients(plrVotes)
end

function mapvote()
	MapsFolder = game.ServerStorage.Maps
	Maps = MapsFolder:GetChildren()
	mapsToVote = {}
	for i, map in ipairs(Maps) do
		table.insert(mapsToVote, map)
	end

	while #mapsToVote > numMapsVoting do
		table.remove(mapsToVote, math.random(1, #mapsToVote))
	end

	plrVotes = {}

	game.ReplicatedStorage:WaitForChild("VotingBegun"):FireAllClients(mapsToVote)

	task.wait(20)

	local highestVotedFor = nil

	local votes = {}
	for i, map in pairs(mapsToVote) do
		votes[map.Name] = 0

		if i == 1 then
			highestVotedFor = map.Name
		end
	end

	for plr, vote in pairs(plrVotes) do

		if votes[vote] then
			votes[vote] += 1

			if votes[highestVotedFor] < votes[vote] then
				highestVotedFor = vote
			end
		end
	end

	game.ReplicatedStorage:WaitForChild("VotingEnded"):FireAllClients()
	newMap = highestVotedFor

end
game.ReplicatedStorage:WaitForChild("Voted").OnServerEvent:Connect(addVote)

game.Players.PlayerRemoving:Connect(removePlayerVote)

while true do
	game.ReplicatedStorage.MessageVisible.Value = true
	game.ReplicatedStorage.MessageText.Value = "Intermission"
	timeEvent = game.ReplicatedStorage.TimeEvent
	IntermissionSong = IntermissonThemes[math.random(1, #IntermissonThemes)]
	IntermissionSong:Play()
	function Timer()

		local timeAmount = 15

		while timeAmount > 0 do

			timeEvent:FireAllClients(timeAmount)

			wait(1)

			timeAmount -= 1

		end

	end
	Timer()
	IntermissionSong:Stop()
	game.ReplicatedStorage.MessageVisible.Value = false
	Gamemode = getNextGamemode()
	GamemodeClone = game.ServerStorage.Gamemodes[Gamemode]:Clone()
	startNewRound()
	game.ReplicatedStorage.RoundStartGuiV.Value = true
	wait(5)
	mapvote()
	wait(3)
	local MapClone = MapsFolder[newMap]:Clone()
	MapClone.Parent = game.Workspace.Map
	MapClone:MakeJoints()
	wait(3)
	for i, v in pairs(game.Players:GetPlayers()) do
		local randomSpawn = MapClone.TeleportSpots:GetChildren()[Random.new():NextInteger(1, #MapClone.TeleportSpots:GetChildren())]
		v.Character.HumanoidRootPart.CFrame = randomSpawn.CFrame
	end
	game.ReplicatedStorage.RoundStartGuiV.Value = false
	giveTool()
	wait(2.5)
	if GamemodeClone.Name == "Gamemode1" then
--gamemode code here--
	elseif GamemodeClone.Name == "Gamemode2" then
--gamemode code here--
	elseif GamemodeClone.Name == "GamemodeClone3" then
--gamemode code here--

You don’t pass the player through the function.

Also, you would need to use a for loop and iterate through every player in order to run the function properly:

for _, plr in ipairs(game.Players:GetPlayers()) do
    giveTool(plr)
end

You should also add some sort of value that indicates whether the player is in the round or not, assuming that’s what this script is for. Otherwise, you’ll give the tool to the player even if they’re not in the current round.

2 Likes

I don’t think the title is accurate enough as I don’t see any physical evidence of .Backpack matching to the error message. Are you perhaps describing a bug with something not happening?

OP runs the giveTool() function without passing the player parameter that the function has. Since Player is nil and they try to get nil.Backpack, it throws the error the title has.

Ah, it seems you are correct about this. Make sure you pass every parameter.

1 Like

“:FindFirstChildOfClass” Should not be used. This is the script.

local Tool = game.ServerStorage.ToolName
local function giveTool(player)
    local backpack = game.Players[tostring(player)]:WaitForChild("Backpack")
    if backpack then
        local tool = Tool:Clone()
        tool.Parent = backpack
    end
end

Also forgot to pass in the player argument. This should work.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.