Need help with inventory server

Hello developers. I have been experiencing this weird problem in my code. Basically, when the starterpack is copied to the backpack the backpack.childadded event is not working.


function InventoryServer.PlayerAdded(plr)
	print("here")
	InventoryServer.Inventories[plr] = {}


	local backpack = plr:WaitForChild("Backpack")
	  
	print("here2")
	 for i,v in pairs(StarterPack:GetChildren()) do
			while not backpack:FindFirstChild(v.Name) do
				task.wait(0)
			end
	 end
	 
	print(backpack:GetChildren())

	for _, tool in pairs(backpack:GetChildren()) do
		if tool:IsA("Tool") then
			InventoryServer.RegisterItem(tool, plr)
		end
	end
	

	backpack.ChildAdded:Connect(function(child)
		if child:IsA("Tool") then
			InventoryServer.RegisterItem(child, plr)
		end
	end)

	backpack.ChildRemoved:Connect(function(child)
		if child:IsA("Tool") then
			InventoryServer.UnregisterItem(child, plr)
		end
	end)
end

It prints up untill here2 then the code stops running there is no warnings or whatsoever in the output.

What I think is happening is the loop never stops so the code doesn’t proceed what I would do either is either task.Spawn(function) or come up with another approach

Have you tried adding a print statement inside this while loop? I’m guessing it’s waiting forever as it can’t find an item in the starterpack that matches the name of an item in the backpack, hence the other print statements not being printed.

	print("here2")
	 for i,v in pairs(StarterPack:GetChildren()) do
			while not backpack:FindFirstChild(v.Name) do
				task.wait(0)
			end
	 end

Also there is no difference between task.wait and task.wait(0) both will yield in a single frame

i used print(v) and it seems to be working fine

Yeah the loop is continuing without a stop but using task.spawn would mess up its purpose

I don’t really get the purpose of that loop

1 Like

If for some reason you want to keep the loop you should move the connections to the top

sup you can just use coroutine.wrap() so it doesnt yield the rest of the code