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 fix this DataStore script? First DataStore.

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.

3 comments

0

What error does it show?

0

No errors it just doesn't work.

0

DataStores needs to be enabled on game settings to work on studio. Do it works on the real game?

1 answer

✓ Accepted answer

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.

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