Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I save a vector3 value from players position?

I have a DataStore script which where every one second it updates the vector3value to the players torso position. In this case it does change the value of the vector3 but on the last line I have an error saying: "Cannot store array in DataStore" once I stop the game.

script located in workspace:

local DataStore = game:GetService("DataStoreService"):GetDataStore("PlayerPos")

game.Players.PlayerAdded:connect(function(player)
	local key = "key-"..player.userId
	
	while wait(1) do
	script:WaitForChild("PlayerPosition").Value = player.Character:WaitForChild("Torso").Position
	print(script:WaitForChild("PlayerPosition").Value)
	
	end
	
	local save = DataStore:GetAsync(key)
	if save then
		script:WaitForChild("PlayerPosition").Value = save[1]

	else
		local load = {script:WaitForChild("PlayerPosition").Value}
		DataStore:SetAsync(key,load)
	end
	
	
end)

game.Players.PlayerRemoving:connect(function(player)
	local key = "key-"..player.userId
	local load = {script:WaitForChild("PlayerPosition").Value}
	DataStore:SetAsync(key,load)
end)

and since I can save the value, I have a line of code were the player teleport's back to its last position. player.Character:WaitForChild("Torso").Position = CFrame.new(Vector3.new(script:WaitForChild("PlayerPosition"))) but it doesn't work, or maybe but don't know where or how to put it. Is there a solution to this? Thank you! p.s: "PlayerPosition" is the Vector3Value inside the script

1 answer

✓ Accepted answer

You should save the position as the individual X, Y and Z coordinates, as you cannot save UserData values (such as Vector3). You can also try something like this:

local ds = game:GetService("DataStoreService")
local lastPos

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local pos = ds:GetDataStore("PlayerPos"):GetAsync("plr_" .. plr.UserId)
		if pos then
			plr.Character:WaitForChild("HumanoidRootPart").CFrame = CFrame.new(pos[1],pos[2],pos[3])
		end
	end)
	plr.CharacterRemoving:Connect(function(char)
		lastPos = char.HumanoidRootPart.Position
	end)
end)
game.Players.PlayerRemoving:Connect(function(plr)
	if lastPos then
		ds:GetDataStore("PlayerPos"):SetAsync("plr_" .. plr.UserId, {lastPos.X,lastPos.Y,lastPos.Z}
	end
end)
game:BindToClose(function()
	wait(3) --give server time to save before closing
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.