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.