StarterPlayer Character randomizer

So basicly I tried a script that, when the player joins He gets a random character (Model) From Server storage but there are some issues it either will Work for like 1 sec and then return to my roblox model or the run system in my game will stop working here is the script:


local characters = game.ServerStorage:WaitForChild("StarterCharacters"):GetChildren()

game.Players.PlayerAdded:Connect(function(player)
	if #characters > 0 then
		local function assignCharacter()

			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()	

			player.Character = newChar
			newChar.Parent = workspace
			local PlayerSpawns = workspace:WaitForChild("PlayerSpawns"):GetChildren()
			player.Character:WaitForChild("HumanoidRootPart").CFrame = PlayerSpawns[math.random(1, #PlayerSpawns)].CFrame
		end

		player.CharacterAdded:Connect(function(c)
			local h = c:WaitForChild("Humanoid")
			h.Died:Connect(function()
				task.wait(3)
				assignCharacter()
			end)
		end)

		assignCharacter()
	else
		print("There are no starter characters in StarterPlayer.")
		player:LoadCharacter()
	end
end)

Try this script instead. Rather than setting the current player to the new character, I named that new character StarterCharacter, parented it into StarterPlayer, then used player:LoadCharacter to reload the character.

local characters = game.ServerStorage:WaitForChild("StarterCharacters"):GetChildren()

local starterChars = {}

for i, char in ipairs(characters) do
	table.insert(starterChars, char)
end

game.Players.PlayerAdded:Connect(function(player)
	if #characters > 0 then
		local function assignCharacter()
			for i, character in pairs(game:GetService("StarterPlayer"):GetChildren()) do
				if character.Name == "StarterCharacter" then
					character:Destroy()
				end
			end

			local function randomCharacter()
				local random = Random.new()
				return starterChars[random:NextInteger(1, #characters)]
			end

			local newChar = randomCharacter():Clone()
			
			newChar.Name = "StarterCharacter"
			newChar.Parent = game:GetService("StarterPlayer")
			
			player:LoadCharacter()
		end

		player.CharacterAdded:Connect(function(c)
			local h = c:WaitForChild("Humanoid")
			h.Died:Connect(function()
				task.wait(3)
				assignCharacter()
			end)
		end)

		assignCharacter()
	else
		print("There are no starter characters in StarterPlayer.")
		player:LoadCharacter()
	end
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.