I’ve been trying to figure out how to use DataStores and I tried to make a script in a click detector that saves the part’s position. When you rejoin and click the part it moves the cube to that part. This is my script :
local DS = game:GetService("DataStoreService")
local BoxPos = DS:GetDataStore("BoxPos")
script.Parent.MouseClick:Connect(function(plr)
local boxData = BoxPos:GetAsync(plr.UserId)
if boxData then
workspace.Box.Position = Vector3.new(boxData:match("(.+), (.+), (.+)"))
else
BoxPos:SetAsync(plr.UserId,000)
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local boxPos = workspace.Box.Position
BoxPos:SetAsync(plr.UserId,tostring(BoxPos))
end)
I don’t know what the issue is as I don’t get any errors about saving but when I click it, it moves it to "0,0,0"
The issue is caused by the creation of the Vector3:
Let’s say we have P = Vector3.new(1,2,3)
. Then we do tostring(P)
, which returns boxData = "1, 2, 3"
.
Now, when you GetAsync, you use :match("(.+), (.+), (.+)")
, which returns one string: “1 2 3”. Passing this variable to Vector3.new is the same as: Vector3.new("1 2 3")
. Since using strings is invalid, the vector returns 0, 0, 0
.
Instead, you want to use a different function. Since you need a table of arguments, we can use string:split
. So, then we would have boxData:split(", ")
which returns {"1","2","3"}
.
We want to pass these numbers as separate parameters, not as table, so we can wrap unpack()
around it.
The full code would be:
if boxData then
workspace.Box.Position = Vector3.new(unpack(boxData:split(", ")))
else
BoxPos:SetAsync(plr.UserId, nil)
end
Let me know if it worked – and don’t hestitate to place a comment if it didn’t!