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

How would I make DataStore work correctly with my script?

I've put this code in a server-script, loadstringenabled, And there are no errors either. And the script doesn't seem to work when trying to test.

wait(1)
game.OnClose = function()
local Data=game:GetService("DataStoreService"):GetDataStore("Load")


game.Players.PlayerAdded:connect(function(plr)
	if plr.DataReady==true then
    local pos = Data:GetAsync(plr.userId)
    if pos then
        plr:FindFirstChild("Character"):MoveTo(Vector3.new(pos.x, pos.y, pos.z))
		end
    end
end)

game.Player.PlayerRemoving:connect(function(plr)
	if plr.DataReady==true then
    local v3 = plr:WaitForChild("Character"):FindFirstChild("Torso").Position
    Data:SetAsync(plr.userId, {x = v3.x, y = v3.y, z = v3.z})
		end
	end)
end

1 answer

✓ Accepted answer

The script only starts operating when the game is closing (that's what line #2 does), which explains why you will never observe any behaviour from it.

I believe if plr.DataReady==true then is not necessary (DataReady is not part of DataStore usage).

Another problem is that you use "WaitForChild" in the PlayerRemoving code to access "Character", which is a field, not a child. "WaitForChild" will therefore never return. Then you use "FindFirstChild" (which is fine), followed by ".Position" (which will error if the Torso doesn't exist -- ex, if the player fell off the edge or glitched through the ground and exited before they had respawned). You should check to see if the Torso exists before accessing its Position.

Now, if it's possible that the Torso might not exist at this point, it may be better to have a loop that occasionally stores the Torso's position in a variable. When the PlayerRemoving code executes, you could use that value if the Torso doesn't exist. (If you store it in a dictionary, be sure to delete the entry from the dictionary to prevent memory leaks.)

4 comments

0

No help.

0

@NotNowSkid Your comment is also no help (ex, what part don't you understand, or isn't working?). If you want help on this site you need to be willing to put work in.

0

You could've helped by fixing/ or editing my code I would've understood better I believe.

0

This site is about learning how to code better, not having other people fix your scripts. That said, delete lines 2, 7, 11, 16, 19, 21. That should get it operating most of the time.

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