Right now i have my leaderstats all set up, when I use the first two scripts below, it goes up by 2. The third script has the leaderstat and datastore creation. All I need is that when my leaderstat goes up, (or down), to save it to the datastores. Help would be appreciated.
client side script to tell server to update leaderstat
local Players = game:GetService("Players")
local NoobPrinter1 = workspace.NoobStuff:WaitForChild("Noob Printer 2")
local function handleChildDestroyed(player)
print("Child '1' destroyed event received for player:", player.Name)
-- Communicate the event to the server
game.ReplicatedStorage.ChildDestroyedEvent:FireServer(player)
end
NoobPrinter1.ChildRemoved:Connect(handleChildDestroyed)
serverside script to update leaderstat
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ChildDestroyedEvent = Instance.new("RemoteEvent")
ChildDestroyedEvent.Name = "ChildDestroyedEvent"
ChildDestroyedEvent.Parent = ReplicatedStorage
local function handleChildDestroyed(player)
if player then
local stats = player:FindFirstChild("leaderstats")
local friendsStat = stats and stats:FindFirstChild("Friends")
if friendsStat and friendsStat:IsA("IntValue") then
friendsStat.Value = friendsStat.Value + 2
print("Leaderstat updated for player:", player.Name)
print("Current value:", friendsStat.Value)
end
end
end
ChildDestroyedEvent.OnServerEvent:Connect(handleChildDestroyed)
server side script to a=create and save leaderstat
local DataStoreService = game:GetService("DataStoreService")
local Players = game:getService("Players")
local CurrencyData = DataStoreService:GetDataStore("CurrencyData")
local CurrencyName = "Friends"
local StartingValue = 0
Players.PlayerAdded:Connect(function(player)
local UserData
local success, errMsg = pcall(function()
UserData = CurrencyData:GetAsync(player.UserId)
end)
if success == false then
local doNotSave = Instance.new("Folder")
doNotSave.Name = "DoNotSave"
doNotSave.Parent = player
else
print("Data loaded!")
end
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Currency = Instance.new("IntValue")
Currency.Name = CurrencyName
Currency.Value = UserData or StartingValue
Currency.Parent = leaderstats
end)
Players.PlayerRemoving:Connect(function(player)
local SavingPath = player.leaderstats:FindFirstChild(CurrencyName)
if player:FindFirstChild("DoNotSave") then
warn("Player data was not saved to avoid data loss.")
else
CurrencyData:SetAsync(player.UserId, SavingPath.Value)
end
end)