I want to create a simple optimization system as a proof of concept and i have got the unloading side of it working but i cant load it back into the workspace.
Right now the system works using player distance and unloads objects into server storage when the player is a certain distance away. The problem is loading the stored objects from server storage to workspace is not working. Anyone got a fix? Here is the code:
– Define the unload and load distances
local UnloadDistance = 60
local LoadDistance = 50
– Create a folder to store the objects in ServerStorage
local ObjectsFolder = Instance.new(“Folder”)
ObjectsFolder.Name = “Gen12_Optimizer_asset_storage”
ObjectsFolder.Parent = game:GetService(“ServerStorage”)
– Create a table to store the objects that need to be managed
local ObjectList = {}
– Function to unload an object
local function unloadObject(object)
– Remove the object from the table
table.remove(ObjectList, table.find(ObjectList, object))
– Check if the object is the Baseplate
if object.Name ~= “Baseplate” then
– Clone the object and move it to the Objects folder in ServerStorage
local clonedObject = object:Clone()
clonedObject.Parent = ObjectsFolder
object.Name = tostring(object.Name)
object:Destroy()
end
end
– Function to load an object
local function loadObject(object)
– Get the cloned object from ServerStorage
local clonedObject = ObjectsFolder:FindFirstChild(object.Name)
– Check if the cloned object exists
if clonedObject then
– Add the object to the ObjectList table
table.insert(ObjectList, clonedObject)
– Move the cloned object back to the game world
clonedObject.Parent = game.Workspace
clonedObject.Name = object.Name
clonedObject = nil
end
end
– Loop through all the objects in the game world
for _, object in pairs(game.Workspace:GetChildren()) do
– Check if the object is a part
if object:IsA(“Part”) then
– Add the object to the ObjectList table
table.insert(ObjectList, object)
end
end
– Connect to the RenderStepped event
game:GetService(“RunService”).RenderStepped:Connect(function()
– Get the player’s character
local character = game.Players.LocalPlayer.Character
– Loop through the ObjectList table
for i, object in pairs(ObjectList) do
– Calculate the distance between the object and the character’s head
local distance = (object.Position - character.Head.Position).Magnitude
– Check if the distance is greater than the unload distance
if distance > UnloadDistance then
– Unload the object
unloadObject(object)
– Check if the distance is less than the load distance and the object is in ServerStorage
elseif distance < LoadDistance and object.Parent == ObjectsFolder then
– Load the object
loadObject(object)
end
end
end)