Character only renders once

Hello!
So I have a local script for my viewport frame.

local camera = Instance.new("Camera", script.Parent)
local Values = game:GetService('ReplicatedStorage'):WaitForChild('Values')
local RunService = game:GetService('RunService')

local Player = game.Players.LocalPlayer

function UpdateCharacter(character)
	
	RunService.Heartbeat:Connect(function()
	
		for i, v in pairs(script.Parent.Icon.Character:GetDescendants()) do
			v:Destroy()
		end
		for i, v in pairs(character:GetChildren()) do
			if v:IsA("BasePart") or v:IsA("Accessory") or v:IsA("Shirt") or v:IsA("Pants") or v:IsA("ShirtGraphic") or v:IsA("BodyColors") or v:IsA("Humanoid") then
				local new = v:Clone()
				new.Parent = script.Parent.Icon.Character
				if v:IsA("Humanoid") then
					new.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
				end
			end
		end
		script.Parent.Icon.CurrentCamera = camera
		camera.CFrame = character.PrimaryPart.CFrame * CFrame.new(0, 1, -3.25) * CFrame.Angles(0, math.rad(180), 0)
		
	end)
end

Values.Speaker:GetPropertyChangedSignal('Value'):Connect(function()
	UpdateCharacter(workspace[Values.Speaker.Value])
end)



The first time, the character gets rendered!
But the second time, the character is still the previous one!
When I set it to my npc in workspace, it still shows my character!
The value in replicatedStorage is the npc though!
So why does this happen? Does anybody know why? I haven’t got any errors at all.

4 Likes

Anybody know my problem?..

1 Like

Because Heartbeat keeps using the old character value so you need to close that old connection everytime you change the speaker:

local camera = Instance.new("Camera", script.Parent)
local Values = game:GetService('ReplicatedStorage'):WaitForChild('Values')
local RunService = game:GetService('RunService')
local Connection

local Player = game.Players.LocalPlayer

function UpdateCharacter(character)
	if Connection ~= nil then
		Connection:Disconnect()
	end
	for i, v in pairs(script.Parent.Icon.Character:GetDescendants()) do
		v:Destroy()
	end
	Connection = RunService.Heartbeat:Connect(function()
		for i, v in pairs(script.Parent.Icon.Character:GetDescendants()) do
			v:Destroy()
		end
		for i, v in pairs(character:GetChildren()) do
			if v:IsA("BasePart") or v:IsA("Accessory") or v:IsA("Shirt") or v:IsA("Pants") or v:IsA("ShirtGraphic") or v:IsA("BodyColors") or v:IsA("Humanoid") then
				local new = v:Clone()
				new.Parent = script.Parent.Icon.Character
				if v:IsA("Humanoid") then
					new.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
				end
			end
		end
		script.Parent.Icon.CurrentCamera = camera
		camera.CFrame = character.PrimaryPart.CFrame * CFrame.new(0, 1, -3.25) * CFrame.Angles(0, math.rad(180), 0)
		
	end)
end

Values.Speaker:GetPropertyChangedSignal('Value'):Connect(function()
	UpdateCharacter(workspace[Values.Speaker.Value])
end)
2 Likes