Checking Whenever Something is added to a Folder

Hello,

So currently this is what I have my workspace set to:

image

As you can see, there is a folder named “PlayersInRound”. I have a script in ServerScriptService, which is running a piece of code that is going to be checking how much content is in the folder whenever it is executed. Which looks like this:

if #game.Workspace.PlayersInRound:GetChildren() >= 2 then
    Run()
end

The problem is however, I want to launch the above piece of code that will launch another function whenever there is actually a change to the folder (whenever something is added or removed to the folder). What would I need to do in order to make that happen, or is it not possible? Thank you.

Note: I am primarily a builder and only recently got back into trying to program, so any advice is helpful :slight_smile:

1 Like

These should help and work for all instances.

5 Likes

This should work

local function check()
	if #game.Workspace.PlayersINRound:GetChildren() >= 2 then
   		Run()
	else
		stopRunning()
	end
end

game.Workspace.PlayersINRound.ChildAdded:Connect(function()
	check()
end)

game.Workspace.PlayersINRound.ChildRemoved:Connect(function()
	check()
end)
2 Likes

Instead of running an Anonymous Function. You could instead just connect the event to the function directly. Like an example below

local Folder = workspace:FindFirstChild("PlayersINRound")

local function check()
	if #Folder:GetChildren() >= 2 then
		print("Woot!")
	end
end

Folder.ChildAdded:Connect(check)
Folder.ChildRemoved:Connect(check)
4 Likes