If statement won't work?

Hello fellow developers,

I have been creating this script for my game. In the script, it counts the number of items in a folder by using the GetChildren() method. When the amount of items gets to 20, the “Stop” value does turn to true, but when it gets under 20 again, the Stop value does not turn to false again. Any help would be appreciated!

Here is the script:

Screenshot 2021-04-10 121213

while true do

   local tab = workspace.Suitcases:GetChildren()

   if #tab >= 20 then 

   elseif #tab < 20 then

   end
end

I guess you could just have this

if #tab >= 20 then
   -- value = true
else
   -- value = false
end

Maybe try this out?

local cases = workspace.Suitcases
local stop = game:GetService("ReplicatedStorage").Stop

local function checkAmount()
	local tab = #cases:GetChildren()
	if tab >= 20 then
		stop.Value = true
	else
		stop.Value = false
	end
end

cases.ChildAdded:Connect(checkAmount)
cases.ChildRemoved:Connect(checkAmount)

I’m not sure if it was something wrong with the way your if statements were set up. Either way, it’s way more optimal to only check if a condition is met rather than a while true do loop, you have ChildAdded and ChildRemoved which can check if the amount of suitcases matches a criteria

2 Likes

Please don’t use a wait() like that. The lowest time that it can wait is around 0.033.

It worked! Thank you! I put in the game.

1 Like

Anytime! if you have anymore issues don’t be afraid to make another post!

And once again, I do recommend you look through for events that can do what you want (usually checking) without the need for loops when possible! It’s much better to only check if the value of what you want to check has increased/decreased rather than constantly checking every interval