Help with assigning a random character upon respawn/death

Hi, I am working on a script relating to random characters upon respawn.
Currently, this is what I have:

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local RandomCharactersFolder = ReplicatedStorage:FindFirstChild("StarterCharacters")
if not RandomCharactersFolder then
	error("RandomCharactersFolder not found in ReplicatedStorage.")
end

local function getRandomCharacter()
	local characters = RandomCharactersFolder:GetChildren()
	local randomIndex = math.random(1, #characters)
	local randomCharacter = characters[randomIndex]:Clone()
	
	print("Assigned character: " .. randomCharacter.Name)
	
	return randomCharacter
end

local function assignRandomCharacter(player)
	local character = getRandomCharacter()
	local humanoid = character:FindFirstChild("Humanoid")
	
	if player.Character then
		-- Teleport the player to the spawn point
		local spawnPoint = workspace:WaitForChild("SpawnLocation")
		if spawnPoint then
			humanoid:MoveTo(spawnPoint.Position)
		end
		player.Character:Destroy()
	end

	character.Name = "StarterCharacter"
	character.Parent = game:GetService("StarterPlayer")
end

Players.PlayerAdded:Connect(function(player)
	assignRandomCharacter(player)

	player.CharacterRemoving:Connect(function(character)
		print("Character removed. Assigning new random character.")
		assignRandomCharacter(player)
	end)

	print(player.Name .. " joined the game.")
end)

Players.PlayerRespawned:Connect(function(player)
	assignRandomCharacter(player)
end)

Currently I am using Players.PlayerRespawned:Connect(function(player) assignRandomCharacter(player) end), but it doesn’t seem to assign the character after the player dies.

Any help about this will be much appreciated.

1 Like

Maybe CharacterAdded can work

5 Likes

You should try what @JAcoboiskaka1121 said. Meanwhile, I would rework your assignRandomCharacter() function (also just remove the character removing event, its redundant):

local function assignRandomCharacter(player)
   local character = getRandomCharacter()
   player.Character = character
   character.Parent = workspace
   player:LoadCharacter()
end
1 Like

I’ve changed it to your function, but now the game doesn’t load and roblox studio crashes once i hit play.

2 Likes