I am attempting to have a player able to see their character in a viewport gui however I am unable to set the parent of the cloned character and it throws the error “Attempted to index nil with parent”
Code
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local ViewportFrame = script.Parent:WaitForChild("ViewportFrame")
local RunService = game:GetService("RunService")
local oldcamera = nil
local oldchar = nil
Player.CharacterAdded:Connect(function(newc)
Character = newc
end)
function update()
if oldcamera ~= nil then
oldcamera:Destroy()
end
if oldchar ~= nil then
oldchar:Destroy()
end
local cam = workspace.CurrentCamera:Clone()
ViewportFrame.CurrentCamera = cam
cam.Parent = ViewportFrame
local clone = Character:Clone()
clone.Parent = ViewportFrame
oldcamera = cam
oldchar = clone
end
RunService:BindToRenderStep("ViewportUpdate", Enum.RenderPriority.Character.Value, update)
This may not necessarily be the source of your problem, but you should consider that there could be times when “update” is called but the character does not exist (e.g. after someone resets their character but before the new character is created).
The character model’s Archivable value is always disabled so that it cannot be saved by any means. Unfortunately, this also makes it so cloning the player will return nothing. You can circumvent this by briefly enabling the value when cloning:
Character.Archivable = true
local Clone = Character:Clone()
Charater.Archivable = false
You shouldn’t be cloning both of those components each frame, it kills your performance.
What you can do, is clone the character one time, but set the Archivable property to true before doing so, and parent that clone to the viewport frame with its own seperate camera, and make it so the viewport character does what the character in the real word does.