So i'm making a game that requires saving but i cant find out how to make a working DataStore, I got this script from Alvinblox on Youtube but it still doesn't work.
local DataStoreService = game:GetService("DataStoreService") local MyDataStore = DataStoreService:GetDataStore('MyDataStore') game.Players.PlayerAdded:Connect(function(player) local stats = Instance.new("Folder") stats.Name = 'leaderstats' stats.Parent = player local cash = Instance.new("NumberValue") cash.Name = 'Cash' cash.Parent = stats local data local success, errormessage = pcall(function() MyDataStore:GetAsync(player.UserId.."-cash") end) if success then cash.Value = data else print('error') print(errormessage) end end) game.Players.PlayerRemoving:Connect(function(player) local success, errormessage = pcall(function() MyDataStore:SetAsync(player.UserId.."-cash",player.leaderstats.Cash.Value) end) if success then print('Saved') else print("Error") end end)
What am i doing wrong?
Note - This is a server script in ServerScriptService
Thanks for reading.
I think it doesn't work because you didn't add an if statement asking if there was data. It wouldn't work because the player wouldn't have any data, so their cash would be equal to nil. Try this:
local DataStoreService = game:GetService("DataStoreService") local MyDataStore = DataStoreService:GetDataStore('MyDataStore') game.Players.PlayerAdded:Connect(function(player) local stats = Instance.new("Folder") stats.Name = 'leaderstats' stats.Parent = player local cash = Instance.new("NumberValue") cash.Name = 'Cash' cash.Parent = stats local data local success, errormessage = pcall(function() MyDataStore:GetAsync(player.UserId.."-cash") end) if success then if data then cash.Value = data end else print('error') warn(errormessage) end end) game.Players.PlayerRemoving:Connect(function(player) local success, errormessage = pcall(function() MyDataStore:SetAsync(player.UserId.."-cash",player.leaderstats.Cash.Value) end) if success then print('Saved') else print("Error") warn(errormessage) end end)
If that doesn't work, then it means you haven't enabled API Services
in your game.