I need help. I’m making a script to change the player character, but it doesn’t work.
The character respawns all the time when the player joins.
local DataStoreService = game:GetService("DataStoreService")
local AvatarCharacterData = DataStoreService:GetDataStore("AvatarCharacterData")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
local data
local success, err = pcall(function()
data = AvatarCharacterData:GetAsync(player.UserId)
end)
if success then
if data then
local newCharacter
for index, char in ipairs(game.ReplicatedStorage.AvatarCharacters:GetChildren()) do
if index == data then
newCharacter = char:Clone()
break
end
end
if newCharacter then
local OldChar = character
newCharacter.HumanoidRootPart.Position = OldChar.HumanoidRootPart.Position
newCharacter.Parent = workspace
player.Character = newCharacter
OldChar:Destroy()
player:LoadCharacter()
game.ReplicatedStorage.ChangeCamera:FireClient(player, newCharacter)
end
elseif not success then
warn(err)
end
end
end)
end)
Yeah, that is the problem, you can not save something when a player has no data yet nor if they just joined the game. You need to save the data when the player leaves.
:LoadCharacter() respawns the player, consequently reloading their original avatar (OldChar) rather than the newly assigned one (newCharacter) - this could be the cause of the issue you described:
Try removing the :LoadCharacter line and see if it makes any difference
local UIS = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local (PUT MODEL NAME HERE) = game.ReplicatedStorage.(MODEL NAME HERE)
local RS = game:GetService("ReplicatedStorage")
local Character = Player.Character
UIS.InputBegan:connect(function(input)
if(UIS:GetFocusedTextBox()) then
return
end
if input.KeyCode == Enum.KeyCode.(KEYCODE) and game.Players.LocalPlayer.Name == "(USERNAME)" then
local Clone = game.ReplicatedStorage.(EVENT NAME HERE)
local pos = Player.Character.HumanoidRootPart.Position
wait(1)
Clone:FireServer(MODEL NAME HERE)
(MODEL NAME HERE).HumanoidRootPart.Position = Player.Character.HumanoidRootPart.Position wait(2)
script.Disabled = true
end
end)
Script: Put this in ServerScriptService
local Player = game.Players.LocalPlayer
local (MODEL NAME HERE) = game.ReplicatedStorage.(MODEL NAME HERE)
local (MODEL NAME HERE) = game.ReplicatedStorage.(EVENT NAME HERE):Clone()
local Clone = game.ReplicatedStorage.(EVENT NAME HERE)
Clone.OnServerEvent:Connect(function(Player, (MODEL NAME HERE))
local WalkSpeed = Player.Character.Humanoid.WalkSpeed
Player.Character.Humanoid.WalkSpeed = 0
Player.Character.Humanoid.WalkSpeed = WalkSpeed
wait(2)
Player.Character = (MODEL NAME HERE)
(MODEL NAME HERE).Parent = workspace
end)
You have to put the model you want the person to be changed to in ReplicatedStorage as well as the event.
Note: I havent perfected this so once the model dies it wont respawn, feel free to change it.