How Would I Datastore Parts, Models, etc

Hello everyone. I am trying to make a simple, short if possible script that will datastore parts, and whatever is inside the part.

My problem is that I can’t seem to make a script that will save the children of the part. I am not the best scripter, so I am trying to avoid anything too complex. However I am very much open to learning something new.

So far I have been able to datastore a table of the properties of a part, but nothing after that like scripts, and click detectors. Additionally, my script is not able to datastore mass amounts of parts.

Any information on this subject would be highly appreciated even if it is not exactly what I am looking for.

Well you could do something like this:

-- Saving --
local models = {}

local currentnumber = 1

for i,v in pairs(plot.Contents:GetChildren()) do
models[currentnumber] = {ModelName = v.Name, ModelCFrame = v.PrimaryPart.CFrame}
end

datastore:SetAsync(key, models)
-- Loading
local dataTable = datastore:GetAsync(key)

local modelCFrame = dataTable.ModelCFrame

local modelName = dataTable.ModelName

local model = game.ReplicatedStorage.Models:FindFirstChild(modelName)

local clone = model:Clone()

clone.Parent = game.Workspace.Plot.Contents

clone.PrimaryPart.CFrame = modelCFrame
1 Like

It’s worth to note that CFrame/Vector3/etc. values won’t be represented in their original form since the DataStore’s built-in JSON serializer doesn’t recognize these values and instead represents them as nil.

local json = game.HttpService:JSONEncode({
	foo = Vector3.new(5, 5, 5) -- some Vector3 value assigned to key 'foo'
})

print(json) --[[ 
output: { "foo": null }  -- oh no! since JSON couldn't recognize this type, it instead replaces it with null.
]]

local table = game.HttpService:JSONDecode(json)

print(table) -- output: {} -- a blank dictionary with no traces of foo

This is where serialization/deserialization would come into play. starmaq has an article about how you would serialize/deserialize objects such as Parts, Models, etc. to get a good understanding of it.

-- coming back to the previous example to see how we would use vector3 values for serialization
local json = game.HttpService:JSONEncode({
	foo = {
		x = 5,
		y = 5,
		z = 5
	}
})

print(json) -- output: { "foo": { x = 5, y = 5, z = 5 } }

local table = game.HttpService:JSONDecode(json)

print(table) -- output: {foo = { x = 5, y = 5, z = 5 }} -- yay! now the vector3 values are successfully serialized/deserialized!
2 Likes