local datastoreserv = game:GetService("DataStoreService")
local redore = datastoreserv:GetDataStore("RedOre")
local players = game:GetService("Players")

players.PlayerAdded:Connect(function(plr)
	print("plr joined detected")
	local bp = plr:WaitForChild("Backpack")
	inv = bp:WaitForChild("inv")
	print(inv.Name)
	inv.redOre = redore:GetAsync(plr.UserId)
	print("saved")
end)
players.PlayerRemoving:Connect(function(plr)
	print("plr left detected")
	local success, err = pcall(function()
		redore:SetAsync(plr.UserId, inv.redOre.Value)
	end)
	if success then
		print("Saved Data!")
	else
		error(err)
	end
end)

This code above isn't working, and everything that is inside of this script exists. My theory is that when the player leaves, their object no longer exists and the code doesn't execute fast enough to save the data. Error is: "Attempt to index redOre with nil"