local dss=game:GetService'DataStoreService':GetDataStore'Data' game.Players.PlayerAdded:Connect(function(player) player.CharacterAdded:Connect(function(character) local getdata=dss:GetAsync(player.UserId) if getdata then character.HumanoidRootPart.CFrame=CFrame.new(getdata[1],getdata[2],getdata[3]) end end) end) game.Players.PlayerRemoving:Connect(function(player) local savedata={ player.Character.HumanoidRootPart.Position.X, player.Character.HumanoidRootPart.Position.Y, player.Character.HumanoidRootPart.Position.Z } dss:SetAsync(player.UserId,savedata) end)
I'm trying to get player's x, y and z positions, store them in a table and load them when player joins with them saved. However, I can't make it work and the output says nothing... I'm very green with data stores and I would very appreciate any help.
Character is printing nil. You could try tracking your character's position using a value instead and update based on that.
game.Players.PlayerRemoving:Connect(function(player) local key = string.format("%s_%s", player.Name, player.UserId) if player.Character then local root_part = player.Character:findFirstChild("HumanoidRootPart") if root_part then if pcall(function() dss:SetAsync(key, root_part.Position) end) then print(string.format("Saved %s position: %s", player.Name, root_part.Position)) else print(string.format("Couldn't save %s position.", player.Name)) end else print(string.format("Couldn't find %s torso.", player.Name)) end else print(player.Name, "/Character is nil") end end)
I personally don't have much experience working with data stores, but I can offer some advice that might help out.
According the wiki, data store keys should be strings, but you are passing integers (player IDs) instead. Consider using something like "player" .. player.UserId
as a key instead.
Keep in mind that a character's default position may be (unfortunately) assigned after the player.CharacterAdded
has been fired, in which case, the position you have assigned to the character will be overridden. There really isn't a clean way to deal with this other than to wait a brief period of time before assigning the character's position so that the character's default position can be assigned first.
Calling GetAsync
every time a player's character loads is inefficient. You should only call it once when the player joins the game and then store its value in a variable for later use.
Calls to data store functions can fail due to networking issues. See here for a better explanation.
Hope this helps.