I am trying to make a door that opens once there is a certain amount of players in the server. I have a script but it works no matter how many players are in the server
Heres the script:
local Players = game:GetService("Players") if #Players:GetPlayers(2) then local door = script.parent do wait (40) door.CanCollide = false door.Transparency = 1 end end
This is a Script that is added into a part
Close but you should put anything in the brackets of line 3 because it will return a table and you should have the script listen for the number of players to change otherwise it will only read your code once...
local Players = game:GetService("Players") local door = script.parent Players.PlayerAdded:Connect(function() --everytime a player joins... if #Players:GetPlayers() >= 2 and door.CanCollide == true then --if there are more than two players and the door isnt open, open the door wait(40) door.CanCollide = false door.Transparency = 1 end end)
If you're using this method it may also be useful to listen for players leaving...
local Players = game:GetService("Players") local door = script.parent local function checkPlayers() --check if the door should be open and act upon it if #Players:GetPlayers() >= 2 and door.CanCollide == true then --if there are more than two players and the door isnt open, open the door wait(40) door.CanCollide = false door.Transparency = 1 elseif #Players:GetPlayers() < 2 and door.CanCollide == false then --if there arent enough players and the door is open, close the door door.CanCollide = true door.Transparency = 0 end end Players.PlayerAdded:Connect(checkPlayers) --everytime a player joins... Players.PlayerRemoving:Connect(checkPlayers) --everytime a player leaves...
Hopefully this works...
Try this:
local Players = game:GetService("Players") local door = script.Parent while true do if #Players:GetPlayers() == 2 then door.CanCollide = false door.Transparency = 1 end wait(.01) end
We use a while loop so the number of players is always updated. If the number of players is 2, then the door will open. Otherwise, it will remain closed.
Remember to add a wait()
when using while true loops, because this prevents the client from crashing.
When you use the :GetPlayers function, it returns a table, so there should be nothing in the brackets.
local Players = 0 game:GetService("RunService").Heartbeat:Connect(function() if Players >=2 then script.Parent.Transparency = 1 script.Parent.CanCollide = false elseif Players <2 then script.Parent.Transparency = 0 script.Parent.CanCollide = true end end) game.Players.PlayerAdded:Connect(function() Players = Players + 1 end) game.Players.PlayerRemoving:Connect(function() Players = Players - 1 end)
try this here i tested it and it seems to work