Need help with position saving datastore

You can write your topic however you want, but you need to answer these questions:
Hi everyone! I’m new to datastores, but I want to start learning them. I’m making a datastore that saves a player’s position from the HumanoidRootPart whenever they leave the game.

The datastore doesn’t save and casts the error “Unable to cast value to Object”.
image

local DataStoreService = game:GetService("DataStoreService")

local DataStore = DataStoreService:GetDataStore("PositionDataStore")


game.Players.PlayerAdded:Connect(function(player)
	player.CharacterRemoving:Connect(function(character)
		local success, errormessage = pcall(function()
			DataStore:SetAsync(player.UserId,player.Character.HumanoidRootPart.Position.X,player.Character.HumanoidRootPart.Position.Y,player.Character.HumanoidRootPart.Position.Z)
		end)

		if success then
			print("success")	
		else
			print("fail")
			warn(errormessage)
		end
	end)
end)

Why dont you do just player.Character.HumanoidRootPart.Position
i could be wrong i dont work with this stuff

2 Likes

Doesn’t work either because of Vector3 stuff. Tried it already. Thanks for the suggestion though!

1 Like

Hey there,

Saving positions in DataStores isn’t something you can do. Instead, you can save a dictionary with the with the x, y, and z coordinates of that position, and when the player joins again, use that dictionary to construct a vector3.

local rootPosition = humanoidRootPart.Position
local positionTable = {
    x = rootPosition.X, 
    y = rootPosition.Y, 
    z = rootPosition.Z
}
DataStore:SetAsync(player.UserId, positionTable)

Then when you receive the data, you can construct a position by doing this

local positionTable = DataStore:GetAsync(player.UserId)
local position = Vector3.new(positionTable.x, positionTable.y, positionTable.z)

Hope this helps :slight_smile: Lemme know if you have any more questions

4 Likes

You passed on a parameter called characterin the CharacterAdded event. You can use that in the SetAsync() part. Or, you can save the HumanoidRootParts cframe instead of it’s position.

1 Like

Will try this out. Thank you very much!

3 Likes

Will try this as well. Thank you!

2 Likes