To save an instance you need to first collect the parts cframe. If your instance is on a plot then you will need to get the parts cframe relative to the plot. To get the instances cframe relative to the plot, you must do this
local relative_CFrame = workspace.Plots.CoordinatePlane.CFrame:inverse() * instance.PrimaryPart.CFrame
CoordninatePlane
would be a big large baseplate that you place your items on:
In the image above, the brown part is the baseplate.
Now, instance
in my code example above is the instance that you are trying to save.
Now, what you will need to do next is add relative_CFrame
to a table, but first we need something to make relative_CFrame
compatible with datastores. What we will need is some kind of converter, a converter that will convert relative_CFrame
into a table, and a converter to convert it back to a table.
Here are a couple of functions you can use for converting:
function cframeToTable(cf) -- A function to convert a cframe to a table, because datastores can't store cframes unfortunately :(
return {cf:GetComponents()};
end
function tableToCframe(t) -- A function to convert a table to a cframe
return CFrame.new(table.unpack(t));
end
You will need these functions. Here is how the code will look like now
function cframeToTable(cf) -- A function to convert a cframe to a table, because datastores can't store cframes unfortunately :(
return {cf:GetComponents()};
end
function tableToCframe(t) -- A function to convert a table to a cframe
return CFrame.new(table.unpack(t));
end
game:GetService("Players").PlayerRemoving:Connect(function(plr)
local cframes = {}
for i, v in next, house:GetChildren() do
local relative_CFrame = workspace.Plots.CoordinatePlane.CFrame:inverse() * v.PrimaryPart.CFrame
table.insert(cframes, {v.Name, cframeToTable(relative_CFrame)})
end
-- Save the cframes table to a datastore
end)
Now what we will need, is some code to load the player’s plot back into the game once they join.
game:GetService("Players").PlayerAdded:Connect(function(plr)
-- Load the table from a datastore
-- Then loop through the table and load the items into the game
for i, v in next, loaded_Table do
if items:FindFirstChild(v[1]) then
local item = items:FindFirstChild(v[1]):Clone()
item.CFrame = workspace.Plot.CoordinatePlane.CFrame * tableToCFrame(v[2])
item.Parent = workspace.Plot.Items
end
end
end)
Now, you might be wondering what items
is. items
should be a folder either in ReplicatedStorage
or ServerStorage
, and the folder holds all the items that the player can place in their house.
If you need any more help / have more question, or if I forgot something please let me know!