Fixing my Datastore script to work with my clicks leaderstat

Hey guys I need help to fix my datastore script to work with my clicks leaderstats

local DataStoreService = game:GetService(“DataStoreService”)
local Players = game:GetService(“Players”)

– Replace ‘YourDataStore’ with the name of your actual DataStore
local playerDataStore = DataStoreService:GetDataStore(“Test1”)

– Function to save player’s leaderstats
local function savePlayerData(player)
local leaderstats = player:FindFirstChild(“leaderstats”)
if leaderstats then
local dataToSave = {}
for , stat in pairs(leaderstats:GetChildren()) do
if stat:IsA(“IntValue”) or stat:IsA(“NumberValue”) then
dataToSave[stat.Name] = stat.Value
end
end
local success, errorMessage = pcall(function()
playerDataStore:SetAsync("Player
" … player.UserId, dataToSave)
end)
if not success then
warn("Failed to save data for player " … player.Name … ": " … errorMessage)
end
end
end

– Connect the save function to the PlayerRemoving event
Players.PlayerRemoving:Connect(savePlayerData)

– Also attempt to save data when the game is shutting down
game:BindToClose(function()
for _, player in ipairs(Players:GetPlayers()) do
savePlayerData(player)
– Adding a small delay to ensure data is processed in order
wait(0.5)
print(“Datastore Saved”)
end
end)

local function loadPlayerData(player)
local success, data = pcall(function()
return playerDataStore:GetAsync(“Player_” … player.UserId)
end)
if success and data then
– Assuming leaderstats already exists; otherwise, you’d need to create it.
local leaderstats = player:FindFirstChild(“leaderstats”)
for statName, value in pairs(data) do
local stat = leaderstats:FindFirstChild(statName)
if stat then
stat.Value = value
print(“Datastore Saved”)
end
end
else
warn("Failed to load data for player " … player.Name)
end
end

Players.PlayerAdded:Connect(loadPlayerData)

5 Likes

please format your code in a codeblock (i think its called codeblock) if you know how to do that

4 Likes

Please make sure to cover your code in three Grave Accents/Backticks at both the start and end like this:
```
Code to put in.
```

The code is correctly formatted:

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

-- Replace 'YourDataStore' with the name of your actual DataStore
local playerDataStore = DataStoreService:GetDataStore("Test1")

-- Function to save player's leaderstats
local function savePlayerData(player)
	local leaderstats = player:FindFirstChild("leaderstats")
	if leaderstats then
		local dataToSave = {}
		for *, stat in pairs(leaderstats:GetChildren()) do
			if stat:IsA("IntValue") or stat:IsA("NumberValue") then
				dataToSave[stat.Name] = stat.Value
			end
		end
		local success, errorMessage = pcall(function()
			playerDataStore:SetAsync("Player" .. player.UserId, dataToSave)
		end)
		if not success then
			warn("Failed to save data for player " .. player.Name .. ": " .. errorMessage)
		end
	end
end

-- Connect the save function to the PlayerRemoving event
Players.PlayerRemoving:Connect(savePlayerData)

-- Also attempt to save data when the game is shutting down
game:BindToClose(function()
	for _, player in ipairs(Players:GetPlayers()) do
		savePlayerData(player)
		-- Adding a small delay to ensure data is processed in order
		wait(0.5)
		print("Datastore Saved")
	end
end)

local function loadPlayerData(player)
	local success, data = pcall(function()
		return playerDataStore:GetAsync("Player_" .. player.UserId)
	end)
	if success and data then
		-- Assuming leaderstats already exists; otherwise, you’d need to create it.
		local leaderstats = player:FindFirstChild("leaderstats")
		for statName, value in pairs(data) do
			local stat = leaderstats:FindFirstChild(statName)
			if stat then
				stat.Value = value
				print("Datastore Saved")
			end
		end
	else
		warn("Failed to load data for player " .. player.Name)
	end
end

Players.PlayerAdded:Connect(loadPlayerData)

Looking at the code, you didn’t notice that you were saving data for this string: "Player" .. player.UserId, and trying to get the saved data using this string: "Player_" .. player.UserId

LINE 18:	playerDataStore:SetAsync("Player" .. player.UserId, dataToSave)
											^ No Underscore/Low Line
LINE 41:	return playerDataStore:GetAsync("Player_" .. player.UserId)
												   ^ Has Underscore/Low Line

You should remove the Underscore/Low Line at line 41 to resolve the problem.

5 Likes

It came with this error
18:12:47.826 Failed to load data for player planeboy2021 - Server - DataStoreScript:56
when I tried that fix, any help?

Also this script used to work with the coins leaderstat but dosen’t with the clicks leaderstat.
Leaderstat code:


-- Function to add coins to a player


-- Function to setup leaderstats for a player
local function setupLeaderstats(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local clicks = Instance.new("IntValue")
    clicks.Name = "Clicks"
	clicks.Value = 0
    clicks.Parent = leaderstats

    -- Start adding coins to the player
   
end

-- Connect the PlayerAdded event to setup leaderstats for each player
Players.PlayerAdded:Connect(setupLeaderstats)

-- Iterate through all existing players and setup leaderstats
for _, player in Players:GetPlayers() do
    setupLeaderstats(player)
end```
3 Likes

Hey! Try this one

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

-- Replace 'YourDataStore' with the name of your actual DataStore
local playerDataStore = DataStoreService:GetDataStore("Test1")

-- Function to save player’s leaderstats
local function savePlayerData(player)
    local leaderstats = player:FindFirstChild("leaderstats")
    if leaderstats then
        local dataToSave = {}
        for _, stat in pairs(leaderstats:GetChildren()) do
            if stat:IsA("IntValue") or stat:IsA("NumberValue") then
                dataToSave[stat.Name] = stat.Value
            end
        end
        local success, errorMessage = pcall(function()
            playerDataStore:SetAsync("Player_" .. player.UserId, dataToSave)
        end)
        if not success then
            warn("Failed to save data for player " .. player.Name .. ": " .. errorMessage)
        end
    end
end

-- Connect the save function to the PlayerRemoving event
Players.PlayerRemoving:Connect(savePlayerData)

-- Also attempt to save data when the game is shutting down
game:BindToClose(function()
    for _, player in ipairs(Players:GetPlayers()) do
        savePlayerData(player)
        -- Adding a small delay to ensure data is processed in order
        wait(0.5)
        print("Datastore Saved")
    end
end)

local function loadPlayerData(player)
    local success, data = pcall(function()
        return playerDataStore:GetAsync("Player_" .. player.UserId)
    end)
    if success and data then
        -- Assuming leaderstats already exists; otherwise, you’d need to create it.
        local leaderstats = player:FindFirstChild("leaderstats")
        for statName, value in pairs(data) do
            local stat = leaderstats:FindFirstChild(statName)
            if stat then
                stat.Value = value
            end
        end
        print("Datastore Loaded")
    else
        warn("Failed to load data for player " .. player.Name)
    end
end

Players.PlayerAdded:Connect(loadPlayerData)
1 Like

Nope still didn’t work. Am I supposed to change anything

2 Likes

Did you confirm that you turned on Enable Studio Access to API Services in the Game Settings?

3 Likes

Yep. I have enabled API Services as it was working before but since i changed the leaderstat to clicks from code it stopped working.

1 Like

The condition on line 43 in the loadPlayerData function says:

LINE 43:	if success and data then

This will be false even if the data is equal to nothing, but the success variable is true. If the player was new, or the data wasn’t saved, it would print out "Failed to load data for player " .. player.Name because data = nil and success = true.

1 Like

I have a textbutton and a script in it where very time you click the textbutton the click leaderstats would go up. But when I leave the game this print(“Datastore Saved”) is not in the output and the datastore still dosen’t save.

clickcounterscript:


-- Function to handle the click event
local function onButtonClick()
    -- Get the player who clicked the button
    local player = game.Players.LocalPlayer
    -- Check if the player and their leaderstats exist
    if player and player:FindFirstChild("leaderstats") then
        local clicks = player.leaderstats:FindFirstChild("Clicks")
        -- If the player has a "Clicks" value in their leaderstats, increment it by 1
        if clicks then
            clicks.Value = clicks.Value + 1
        else
            -- If the player does not have a "Clicks" value, create it and set its value to 1
            local newClicks = Instance.new("IntValue")
            newClicks.Name = "Clicks"
            newClicks.Value = 1
            newClicks.Parent = player.leaderstats
        end
    end
end

-- Connect the function to the button's click event
textButton.MouseButton1Click:Connect(onButtonClick) ```
2 Likes

Oh well, It seems like you forgot to add currency you want to save

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

-- Replace 'YourDataStore' with the name of your actual DataStore
local playerDataStore = DataStoreService:GetDataStore("Test1")

-- Function to save player’s leaderstats
local function savePlayerData(player)
    local leaderstats = player:FindFirstChild("leaderstats")
    if leaderstats then
        local dataToSave = {}
        for _, stat in pairs(leaderstats:GetChildren()) do
            if stat:IsA("IntValue") or stat:IsA("NumberValue") then
                dataToSave[stat.Name] = stat.Value
            end
        end
        local success, errorMessage = pcall(function()
            playerDataStore:SetAsync("Player_" .. player.UserId, dataToSave)
        end)
        if not success then
            warn("Failed to save data for player " .. player.Name .. ": " .. errorMessage)
        end
    end
end

-- Connect the save function to the PlayerRemoving event
Players.PlayerRemoving:Connect(savePlayerData)

-- Also attempt to save data when the game is shutting down
game:BindToClose(function()
    for _, player in ipairs(Players:GetPlayers()) do
        savePlayerData(player)
        -- Adding a small delay to ensure data is processed in order
        wait(0.5)
        print("Datastore Saved")
    end
end)

-- Function to add coins to a player
local function addClicks(player)
    local leaderstats = player:FindFirstChild("leaderstats")
    if leaderstats then
        local clicks = leaderstats:FindFirstChild("Clicks")
        if clicks then
            clicks.Value = clicks.Value + 1
        end
    end
end

-- Function to setup leaderstats for a player
local function setupLeaderstats(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local clicks = Instance.new("IntValue")
    clicks.Name = "Clicks"
    clicks.Value = 0
    clicks.Parent = leaderstats

    -- Connect the click event to addClicks function
    player.MouseButton1Click:Connect(function()
        addClicks(player)
    end)
end

-- Connect the PlayerAdded event to setup leaderstats for each player
Players.PlayerAdded:Connect(setupLeaderstats)

-- Iterate through all existing players and setup leaderstats
for _, player in ipairs(Players:GetPlayers()) do
    setupLeaderstats(player)
end
2 Likes

Was the player data never saved at all ever since?

2 Likes

Yes. And also where do I put the script in?

1 Like

Put your script on ServerScriptService

2 Likes

Do you have the Workspace.SignalBehavior property set to Deferred? Try setting it to Immediate instead if it isn’t, then try again.

2 Likes

Came with this error
18:45:45.234 MouseButton1Click is not a valid member of Player “Players.planeboy2021” - Server - Script:62

When I added a script and disable the all scripts

1 Like

Where is that in workspace? I cant find it

1 Like

It’s a property in the Properties Tab.

1 Like

I now have that to immediate but still got this error.
18:49:10.616 MouseButton1Click is not a valid member of Player “Players.planeboy2021” - Server - Script:62

4 Likes

I think it’s because “Onclick” function is not needed here. Try this script

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

-- Replace 'YourDataStore' with the name of your actual DataStore
local playerDataStore = DataStoreService:GetDataStore("Test1")

-- Function to save player’s leaderstats
local function savePlayerData(player)
    local leaderstats = player:FindFirstChild("leaderstats")
    if leaderstats then
        local dataToSave = {}
        for _, stat in pairs(leaderstats:GetChildren()) do
            if stat:IsA("IntValue") or stat:IsA("NumberValue") then
                dataToSave[stat.Name] = stat.Value
            end
        end
        local success, errorMessage = pcall(function()
            playerDataStore:SetAsync("Player_" .. player.UserId, dataToSave)
        end)
        if not success then
            warn("Failed to save data for player " .. player.Name .. ": " .. errorMessage)
        end
    end
end

-- Connect the save function to the PlayerRemoving event
Players.PlayerRemoving:Connect(savePlayerData)

-- Also attempt to save data when the game is shutting down
game:BindToClose(function()
    for _, player in ipairs(Players:GetPlayers()) do
        savePlayerData(player)
        -- Adding a small delay to ensure data is processed in order
        wait(0.5)
        print("Datastore Saved")
    end
end)

-- Function to setup leaderstats for a player
local function setupLeaderstats(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local clicks = Instance.new("IntValue")
    clicks.Name = "Clicks"
    clicks.Value = 0
    clicks.Parent = leaderstats
end

-- Connect the PlayerAdded event to setup leaderstats for each player
Players.PlayerAdded:Connect(setupLeaderstats)

-- Iterate through all existing players and setup leaderstats
for _, player in ipairs(Players:GetPlayers()) do
    setupLeaderstats(player)
end

1 Like