Infinite yield possible on 'Players.kacperek3636:WaitForChild("leaderstats2")'

Hi everyone, i was testing my Gui game named “The Ultimate Elevator” on my main account, and i kept getting this error, i tried many things but it still didnt work. The error appeared from my data store script.

The “leaderstats2” was literally inside the player, i’m really confused why and how this error appeared:
image

This is the data store script i made:

local dss = game:GetService("DataStoreService")
local ds = dss:GetDataStore("ElevatorLevel")

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)

	local leaderstats = player:WaitForChild("leaderstats2") -- This is where the error is

	local ElevatorLevel = leaderstats.ElevatorLevel

	local data
	local success, errormessage = pcall(function()
		data = ds:GetAsync(player.UserId.."-ElevatorLevel")
	end)

	if success then
		ElevatorLevel.Value = data
	else
		warn(errormessage)
		print("error loading data")
	end
end)

game.Players.PlayerRemoving:Connect(function(player)

	local success, errormessage = pcall(function()
		ds:SetAsync(player.UserId.."-ElevatorLevel", player.hiddenLeaderstats.ElevatorLevel.Value)
	end)

	if success then
		print("player data saved.")
	else
		print("failed to save data")
		warn(errormessage)
	end
end)

I don’t think you look in the Players service for this information.
You should be looking in the player in the workspace.

I don’t think the player in the workspace will have the property named “UserId”

Just check both while testing.
Select your player in the workspace and the one in the Players service.
Compare both of them.

It may be something simple as well, like lag in your game causing the loading of a Player taking too long for the WaitForChild to work. If it takes longer than 5 seconds it’ll call infinite yield possible (see the link).

This is a warning telling you that an infinite yield is possible; which means that it’ll continue searching for it forever. WaitForChild will give you this warning when no timeout argument is provided and it exceeds 5 seconds in searching.

It’s best to avoid WaitForChild as much as possible for this specific reason, only using it when absolutely necessary. I would recommend keeping the creation of leaderstats2 and setting the value of any datastores within the same script. However, if it was absolutely necessary to do this knowing that it’s possible the leaderstats2 won’t be there, you should first use FindFirstChild to check if it’s already there, and if it’s not there, you would then call WaitForChild as a fallback.