How to use an if statement with WaitForChild()

  1. What do you want to achieve? I’m trying to make a gui shop system that when the player joins the game, the text of a text label changes depending on if a player owns and item or not.

  2. What is the issue? The problem is that when I use waitforchild to see if a player owns the item and they don’t, I get an infinite yield error.

  3. What solutions have you tried so far? I’ve tried searching for solutions but found none.

local player = game.Players.LocalPlayer
local pc = player.leaderstats.PuppyCoins

local frame = script.Parent.Parent
local equipped = player.ToolEquipped
local item = frame:FindFirstChild("ItemName")
local ItemsOwned = player:FindFirstChild("ItemsOwned")
local cost = frame:FindFirstChild("Cost")

local db = false


if ItemsOwned:WaitForChild(item.Value) then--this is where the problem is
	if equipped.Value ~= item.Value	then
		script.Parent.Text = "Equip"
	end
	if equipped.Value == item.Value then
		script.Parent.Text = "Equipped"
	end
else
	if equipped.Value == nil then
		print("Never Bought a thing")
		script.Parent.Text = "Equipped"
		game.ReplicatedStorage.OwnedEvent:FireServer(ItemsOwned, item)
		game.ReplicatedStorage.EquippedEvent:FireServer(equipped, item)
	end	
end

print("here")
equipped.Changed:Connect(function()
	if ItemsOwned:FindFirstChild(item.Value) and equipped.Value ~= item.Value then
		script.Parent.Text = "Equip"
	end
end)

script.Parent.MouseButton1Down:Connect(function()
	if ItemsOwned:FindFirstChild(item.Value) then
		if equipped.Value ~= item.Value then
			script.Parent.Text = "Equipped"
			game.ReplicatedStorage.EquippedEvent:FireServer(equipped, item)
		end	
	end
end)

1 Like
local Item = ItemsOwned:WaitForChild(item.Value)
if Item then
-- code
end

It still has the infinite yield error.

try to use :FindFirstChild instead.

infinite yeild error means that what youre looking for doesnt exist in the location you are looking. two ways to go about this; 1 the WaitForChild function has a second argument which is a time limit for how long the function runs before moving on i.e. WaitForChild(‘soup’, 1) will search for soup for only 1 second before returning nil. 2 is you use FindFirstChild inside the if statement. id recommend you use option 2 as thats pretty much standard and intended practice

1 Like

FindFirstChild() didn’t work before but now it does. Thanks!

1 Like