I have a little story game and i need to wait until the player has a certain item in thier backpack.
I thought i could do this but it just errors. ( MilkCarton is not a valid member of Backpack “Players.nico_qwer.Backpack” )
This is in a local script
local Player = game.Players.LocalPlayer
repeat wait() until Player.Backpack.MilkCarton ~= nil
print("The player has a milk carton")
How could i tell the script that i know it isn’t there yet, i just want it to wait until it is?
Instead of waiting until it’s there and stopping the entire script, use remote events to communicate the information that the player received the milk carton.
It works, but after a few seconds it does me a warn ( Infinite yield possible on ‘Players.nico_qwer.Backpack:WaitForChild(“MilkCarton”)’ )
Any idea how to signal to the game it might take longer than expected?
It’s warning you that because after a few seconds of it not finding the carton, it assumes that it may infinitely yield. If you’re certain that the carton will soon come, you can just ignore it. Though if it bothers you you’ll have to make whatever happens when the carton is in their backpack happen when the carton changes ancestry, which depends on how the carton is being given
There is actually kinda a more efficient way to do this. repeat wait() is really inefficient. repeat task.wait() is kinda machine intensive. You could go for this:
function WaitForChild(parent,ChildName)
local child = Parent.ChildAdded:Wait()
if child.Name ~= childName then
task.spawn(WaitForChild(parent,ChildName))
return
end
-- Your code here
print("Player has "..ChildName)
end
task.spawn(WaitForChild(Player.Backpack,"MilkCarton"))