As you can tell by the title, I need help with making a custom character spawning script, it works normally when you try to spawn in the first time, but when you try to respawn, it behaves very weirdly: as shown in the video
2020-06-15 16-30-36|video
This is the code:
local playerRemote = script.Parent:WaitForChild("Player")
local serverStorage = game.ServerStorage
local player = playerRemote.OnServerEvent:Wait()
local replicatedStorage = game.ReplicatedStorage
local Characters = replicatedStorage:WaitForChild("Characters")
local SetSubject = replicatedStorage:WaitForChild("SetSubject")
local loadCharacterRemote = script.Parent:WaitForChild("LoadCharacter")
local heroMissionGui = game.ServerStorage:WaitForChild("UI"):WaitForChild("HeroMissionGui")
local villainMissionGui = game.ServerStorage:WaitForChild("UI"):WaitForChild("VillainMissionGui")
loadCharacterRemote.OnServerEvent:Connect(function(player, currentCharacter, classObject)
local ChosenCharacter = Characters[currentCharacter.Name]:Clone()
local isHeroBool = ChosenCharacter.IsHero
local guiClone
if isHeroBool.Value == true then
guiClone = heroMissionGui:Clone()
else
guiClone = villainMissionGui:Clone()
end
local ranBefore = false
local function makeCharacter()
local CurrentCharacter = player.Character
local class = tostring(classObject.Value)
local classScriptFolder = serverStorage.ScriptStorage["Class"..class]
local LocalScripts = {}
for index2,item2 in pairs(classScriptFolder:GetChildren()) do
if item2:IsA("LocalScript") or item2:IsA("Script") then
table.insert(LocalScripts,item2:Clone())
else
item2:Clone().Parent = ChosenCharacter
end
end
CurrentCharacter.Health:Clone().Parent = ChosenCharacter
table.insert(LocalScripts,CurrentCharacter.Animate:Clone())
ChosenCharacter.Parent = workspace
if ranBefore == false then
ranBefore = true
ChosenCharacter.Name = player.Name
end
player.Character = ChosenCharacter
for index2,item2 in pairs(LocalScripts) do
item2.Parent = ChosenCharacter
end
guiClone.Parent = player.PlayerGui
SetSubject:FireClient(player,ChosenCharacter.Humanoid)
local Connection
end
makeCharacter()
local function onDied()
wait(game.Players.RespawnTime)
player:LoadCharacter()
wait(1)
makeCharacter()
end
ChosenCharacter.Humanoid.Died:Connect(onDied)
end)