How to make a function run every time a new child is added?

Hi! I’m working on a game where you can choose which character to spawn in as. I managed to get the script to work (after approximately 137.8 tries) but it only works when I join. Here’s the code:

function spawnBlock() 
	local blockClone =game.ServerStorage.Block:Clone()
	blockClone.Parent= game.StarterPlayer
	blockClone.Name=("StarterCharacter")
	game.Players:FindFirstChild("cedarwaxwing2"):LoadCharacter()
	game.StarterGui.AnimalChoice.Enabled= false
end

	script.Parent.MouseButton1Click:Connect(spawnBlock)

(Instead of loading the character every time a new child is added to Players, it only loads the character when I’m added.)
I’ve looked everywhere and tried asking my friend (who’s really good at scripting) but neither of us could figure it out.
Thank you! :smiley:

Is this a local script? Since you are doing MouseButton1Click so I’d assume its a localscript correct?

game.Players.PlayerAdded:Connect(function(plr)
plr:LoadCharacter()
-- your code
end)
1 Like

No, but that probably explains why i have to click twice :laughing:

If script dont working, you can make RemoteEvent.
In local script call RemoteEvent
and in script accept this remoteevent

game.Workspace.RemoteEvent.OnServerEvent:Connect(function(plr)
-- code with PlayerAdded()
end)