Script is failing to parent the character of the player to a folder

When a new player joins my game, I want their character in the Workspace to be moved to a folder named “Characters”. Here is a photo of the hierarchy:

image

To do this, I wrote a script in the server as shown:

-- services
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")

-- variables
local characters = Workspace:WaitForChild("Characters")

-- player join
Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        while not character.Parent do
            character.AncestryChanged:wait()
        end
        character.Parent = characters
    end
end

However, when I test it, this is the outcome:

image

My character is obviously not parented to the “Characters” folder. And here is the error thrown by the script:

image

Why is this happening and how do I fix it?

Add a wait() before setting the parent.

Turns out if I just add a wait(3) or some sort of constant delay, everything works out.

If I were you I’d parent after the CharacterAppearenceLoaded event, or I’d add a WaitForChild(“Humanoid”) and do the parenting after that.
Also there already is a global variable for Workspace you could use instead of defining workspace with a local variable