Random Player Selector Is Selecting Every Player

So I’m Trying To Make A Random Player Selector And It Makes The Value In Every Player,

Module Script

local KingDataModule = {}


function KingDataModule.IsThereAKing(player)
	for i, v in pairs(game.ReplicatedStorage.Players:GetDescendants()) do
		if not v:FindFirstChild("King") then
			
			KingDataModule.RandomKing(player)
			
			return
		else
			
			print(player.Name.." Is The King")
			
		end
	end
end

function KingDataModule.RandomKing(player)
	local PlayerFolder = game.ReplicatedStorage.Players:GetChildren()
	local PlayerFolderRandom = PlayerFolder[math.random(1,#PlayerFolder)]

	local KingTag = Instance.new("BoolValue", PlayerFolderRandom)
	KingTag.Name = "King"
	KingTag.Value = true
	KingTag.Parent = PlayerFolderRandom
end

return KingDataModule

Script

local KingDataModule = require(script.KingDataModule)
local WaitTimer = 1

game.Players.PlayerAdded:Connect(function()
	local Players = game:GetService("Players")
	for i, player in pairs(Players:GetPlayers()) do
		print(player.Name)
		if not game.ReplicatedStorage.Players:FindFirstChild(player.Name) then
			local PlayerTag = Instance.new("StringValue")
			PlayerTag.Name = player.Name
			PlayerTag.Value = ""
			PlayerTag.Parent = game.ReplicatedStorage.Players
			
			wait(WaitTimer)

			KingDataModule.IsThereAKing(player)

		else
			warn("Player Already Has A Value")
		end
	end

end)

Image
image

From what I can tell in your code, the module is searching through every player that doesn’t have King status and gives it to them.

Try this as your module:

local KingDataModule = {}


function KingDataModule.IsThereAKing()
	local HaveKing=false
	for i, v in pairs(game.ReplicatedStorage.Players:GetDescendants()) do
		if v:FindFirstChild("King") then HaveKing=true end
	end
    if HaveKing==false then KingDataModule.RandomKing() end
end

function KingDataModule.RandomKing()
	local PlayerFolder = game.ReplicatedStorage.Players:GetChildren()
	local PlayerFolderRandom = PlayerFolder[math.random(1,#PlayerFolder)]

	local KingTag = Instance.new("BoolValue", PlayerFolderRandom)
	KingTag.Name = "King"
	KingTag.Value = true
	KingTag.Parent = PlayerFolderRandom
end

return KingDataModule
2 Likes

you are doing a loop on

so thats why its gonna choose every player