How to disable a Script if 1 or lesser than 1 players detected

  1. What do you want to achieve?
    I want to make a script, which disables a script if there is 1 or lesser than 1 player found in a game.

  2. What is the issue? Include screenshots / videos if possible!
    So i tried to make a Player Count Code which searches for available players, and if 1 or lesser than 1 player has been detected, it should disable a script…
    –Pics–

  3. What solutions have you tried so far?
    if playercount<1 and script.RolePickerScript.Disabled == true then
    script.RolePickerScript.Disabled = false

If anybody could explain what i should do/add, i would really appreciate it…

if #game:GetService'Players':GetPlayers() < 1 then
    -- do stuff
end

I noticed in your script that you are checking for player count “<1” which should be “<=1”
More simplified version of what you are doing:

 local Players = game:GetService("Players")
     
 Players.PlayerAdded:Connect(function(Plr)
     if #Player:GetPlayers() <= 1 then
        YourScript.Disabled = true
     end
 end)
1 Like

I would not advise disabling the scripts, but integrating the functionality of the RolePickerScript into the same script. In this script, you want to check whether total players are x > 1 and otherwise ignore the part if there is insufficient amount of players.

Disabling scripts and re-enabling them seems to not work accurately. It also creates a “race condition” between this script and the other one. I believe these are all the disadvantages.

2 Likes

This would only ever fire once, you would want to be also using Players.PlayerRemoving to detect when players have left the game.

local Players = game:GetService("Players")

local function PlayersChanged()
	local PlayerCount = #Players:GetPlayers()
	if PlayerCount <=1 then
		script.RolePickerScript.Disabled = true
	else
		script.RolePickerScript.Disabled = false
	end
end

Players.PlayerAdded:Connect(PlayersChanged)
Players.PlayerRemoving:Connect(PlayersChanged)

I also agree that this should be implemented directly into the RolePickerScript instead of disabling it from another script.

3 Likes

Thanks a lot for helping me! But the code actually had some problems in it, which i could easily modify,
so all i did was change the
if PlayerCount <=1 then
game.ServerScriptService.RolePickerScript.Disabled = true
thanks a lot for helping me out!

Thanks a lot for explaining the Code to me! Really appreciate it for helping me out!