How do I fix this rendering script?

I was working on a rendering script and then I ran into an issue where when the player resets their character, the object that was rendered out doesn’t render in. Here’s what I’m talking about:


And here’s the script I’m using. This script is located in StarterCharacterScripts:

    local Players = game:GetService("Players")
    local ReplicatedStorage = game:GetService("ReplicatedStorage")
    local Workspace = game:GetService("Workspace")
    local RunService = game:GetService("RunService")

local LocalPlayer = Players.LocalPlayer

local RenderCache = ReplicatedStorage:WaitForChild("RenderCache")

local Character = script.Parent

local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")

local RenderDistance = 40

local Render = Workspace:WaitForChild("Render")

local Parts = {}

function Scan()
	for _, Object in next, Render:GetChildren() do
		table.insert(Parts, Object)
		Object.Parent = RenderCache
	end
end

function GetPart(Object)
	if (Object:IsA("BasePart")) then
		return Object
	else
		for _, Obj in next, Object:GetChildren() do
			return GetPart(Obj)
		end	
	end
	return nil
end

function Update()
	for _, v in next, Parts do
		local Part = GetPart(v)

		if (Part) then
			local Distance = (Part.CFrame.p - HumanoidRootPart.CFrame.p).Magnitude

			Distance = math.floor(Distance + 0.5)

			if (Distance <= RenderDistance) then
				v.Parent = Render
			else
				v.Parent = RenderCache
			end	
		end
	end
end

Scan()
RunService:BindToRenderStep("RenderSys", 1, Update)
1 Like

The problem seems to be that every time you reset, the Parts table resets to an empty table as well. So when you respawn, make sure you put objects in the RenderCache into the Parts table as well.

If you replace the old Scan function with the one shown below, it will include the wall inside of the RenderCache in the Parts table.

function Scan()
	for _, Object in next, Render:GetChildren() do
		table.insert(Parts, Object)
		Object.Parent = RenderCache
	end
        for _, Object in next, RenderCache:GetChildren() do
		table.insert(Parts, Object)
		Object.Parent = RenderCache
	end
end
1 Like

Oh that worked! Thank you so much for your help!

1 Like

old reply but is there a way to slow this script down? when i open Script Performance, it shows This Script over 60- 70% activity, running 20 times per second. when i die it lowers to 35-45 activity. And since you cant use values as low as wait(0.0001) to slow it down the scanning section of the code. Any suggestions how to fix this?