Can somebody help me with an AI to automatically choose a character?

So basically there are 11 characters you can choose from in my game. If a player hasn’t chosen a character before the game starts, then the game will find that player and will randomly choose a character for them.

The trouble I’m having is the actual AI. So I set up a randomizer to choose a character, but if it chooses a character somebody else already chosen, it gets really glitchy.

So I made it keep choosing a random character until it chooses an available one. The only problem is if there were multiple players who haven’t chosen a character already then it would be doing all of them at the same time, and multiple of them can land on the same character at the same time which will make it glitchy again.

I just need a simple AI that can choose an available character for all the players who haven’t chosen one.

What I suggest doing is keeping track of the players who have chosen their character in a table. Once the timer is up and the player still hasn’t chosen a character, then you loop through all the players and check if they’re in the table. If not, we use a placeholder table or however you’re fetching the 11 characters on the server, and picking a random character from there. Hope this helps :slight_smile:

local players = game:GetService('Players')
local plrTable = {}
local characters = { -- doesn't have to be hardcoded to a table like this, you can fetch the characters through a folder nstead
    'Piggy',
    'SpongeBob',
    'Sam',
    'Jack',
    'Smiley'
}

if not plrTable[player.UserId] then 
	plrTable[player.UserId] = character
	table.remove(characters, characters[character]) -- remove the chosen character through howerver you're fetching it, e.g using remote to pass through character name 
	-- send what characters cant be chosen back to client?
else 
	return
end

-- game starts -- inside loop?
for _,plrs in pairs(players:GetPlayers()) do
	if not plrTable[plrs.UserId] then -- check what chosen characters are not found
		local randomSkin = characters[math.random(1, #characters)] -- choose random one from placeholder Table
		plrTable[plrs.UserId] = randomSkin 
		table.remove(characters, characters[randomSkin])
	end
end
1 Like