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

script to store data for coins but when i leave it doesnt save what did i do wrong??

here is my script for the data store

local DataStoreService = game:GetService("DataStoreService")

local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local cash = Instance.new("IntValue")
		cash.Name = "Cash"
		cash.Parent = leaderstats
	
	local data	
	local success, errormessage = pcall(function()
		data = myDataStore:GetAsync(player.UserId.."-cash")
	end)
	
	if success then
		cash.Value = data
	else
		print("There was a error whilist getting your data")
		warn(errormessage)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	
	local success, errormessage = pcall(function()
		myDataStore:GetAsync(player.UserId.."-cash",player.leaderstats.Cash.Value)
	end)
	
	if success then
		print("Player Data sccessfully saved!")
	else
		print("There was a error when saving your data")
		warn(errormessage)
	end
	
end)

1 comment

0

(I've edited your question to add the code block - there's a little "Lua" icon you can click (to the right of Bold/Italics/etc) for it.)

1 answer

  1. You need to use SetAsync not GetAsync when the player leaves
  2. You need to use game:BindToClose to make sure that the server stays open after all players leave long enough to save their data.

Alternatively, if you use something like ProfileService, it takes a bit of getting used to, but it handles all that in addition to auto-saving, session locking, and more.

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