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

Datastore not saving dating and not giving an error?

This script is a datastore for leaderstats. Obviously, its supposed to save, but I doesn't. It worked at first but I changed some things in in and now it doesn't work, whats wrong?

Code:

local dataStoreService = game:GetService("DataStoreService")
local myDataStore = dataStoreService:GetDataStore("MainDataStore")

local playersLeft = 0

-- Load leaderstats
game.Players.PlayerAdded:Connect(function(player)

	playersLeft = playersLeft + 1
	
	-- Leaderstats 
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	-- Coins
	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Parent = leaderstats
	
	-- Gems
	local gems = Instance.new("IntValue")
	gems.Name = "Gems"
	gems.Parent = leaderstats
	
	-- Levels
	local levels = Instance.new("IntValue")
	levels.Name = "Level"
	levels.Parent = leaderstats

	-- Load data

	local PlayerUserId = player.UserId -- Player key to store data

	local player_data
	
	-- Data to load in
	local dataTable1 = {
		Coins = player.leaderstats.Coins.Value;
		Gems = player.leaderstats.Gems.Value;
		Levels = player.leaderstats.Level.Value;
	}

	local success, errorMessage = pcall(function()
		player_data = myDataStore:GetAsync(PlayerUserId)
	end)

	-- Load data

	if success then
		coins.Value = dataTable1.Coins
		gems.Value = dataTable1.Gems
		levels.Value = dataTable1.Levels
	end
end)

local bindableEvent = Instance.new("BindableEvent")

-- Player leaves
game.Players.PlayerRemoving:Connect(function(player)

	local playerUserId = player.UserId -- Player key

	-- Data table
	local dataTable2 = {
		Coins = player.leaderstats.Coins.Value;
		Gems = player.leaderstats.Gems.Value;
		Levels = player.leaderstats.Level.Value;
	}

	local success, errorMessage = pcall(function()
		myDataStore:SetAsync(playerUserId, dataTable2)

		playersLeft = playersLeft - 1

		bindableEvent:Fire()
	end)

	if success then
		print("Data saved")
	else
		print("Error saving data")
		warn(errorMessage)
	end
end)

if playersLeft > 0 then
	bindableEvent.Event:Wait()
end

1 comment

0

What is dataTable1 for? Since it's stated before you fetch the data, it will automatically become a zero or nil. Why not just use "player_data.Coins, player_data.Gems", etc etc?

1 answer

Have you enabled "Allow HTTP Requests" and "Enable Studio Access to API Services"? It is in the Game settings.

1 comment

0

Yes, I checked and It would give an error on line 84 if it wasn't

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