I made a small change to the code. Instead of using .CharacterAdded:Connect(), I used .CharacterAdded:Wait(). See if that makes any change to the error. I tested it out and it works for me.
-- In a script in ServerScriptService
local characters = game.ServerStorage:WaitForChild("StarterCharacters"):GetChildren() -- replace with where the folder is and the name of the folder
game.Players.PlayerAdded:Connect(function(player)
if #characters > 0 then
local starterChars = {}
for i, char in ipairs(characters) do
table.insert(starterChars, char)
end
local function randomCharacter()
local random = Random.new()
return starterChars[random:NextInteger(1, #characters)]
end
local newChar = randomCharacter():Clone()
local oldChar = player.Character or player.CharacterAdded:Wait()
local oldCFrame = oldChar:GetPrimaryPartCFrame()
player.Character = newChar
newChar.Parent = workspace
newChar:SetPrimaryPartCFrame(oldCFrame)
oldChar:Destroy()
else
print("There are no starter characters in StarterPlayer.")
end
end)
I’m basing my code off of another dev forum post on setting a player’s character.