How Do I Make A DataStore For This Leaderstats Script

game.Players.PlayerAdded:Connect(function(player)

local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"

local Strength = Instance.new("IntValue", leaderstats)
Strength.Name = "Strength"
Strength.Value = 1

local Exp = Instance.new("IntValue", leaderstats)
Exp.Name = "Exp"
Exp.Value = 0

local RequiredExp = Instance.new("IntValue", player)
RequiredExp.Name = "RequiredExp"
RequiredExp.Value = Strength.Value * 100

Exp.Changed:Connect(function(Changed)
	if Exp.Value == RequiredExp.Value then
		Exp.Value = 0
		
		Strength.Value += 1
		RequiredExp.Value = Strength.Value * 100
	end
end)

end)

This should work:

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

local function CrateStats(Player)
  local Leaderstats = Instance.new("Folder")
  Leaderstats.Name = "leaderstats"
  Leaderstats.Parent = Player

  local Strength = Instance.new("IntValue", Leaderstats)
  Strength.Name = "Strength"
  Strength.Value = 1

  local Exp = Instance.new("IntValue", Leaderstats)
  Exp.Name = "Exp"
  Exp.Value = 0

  local RequiredExp = Instance.new("IntValue", Player)
  RequiredExp.Name = "RequiredExp"
  RequiredExp.Value = Strength.Value * 100
end

local function LoadData(Player)
  local Success, Result = pcall(function()
    DataStore:GetAsync(Player.UserId)
  end
  if Success then
    if Result then
      for _, Info in pairs(Result) do
        local Value = Player.leaderstats[Info[1]]
        Value.Value = Info[2]
      end
    end
  end
end

local function OnPlayerAdded(Player)
  local Leaderstats = CreateStats(Player)
  repeat
    task.wait()
  until Leaderstats
  LoadData(Player)
  Exp.Changed:Connect(function(Changed)
    if Exp.Value == RequiredExp.Value then
      Exp.Value = 0	
      Strength.Value += 1
      RequiredExp.Value = Strength.Value * 100
    end
  end)
end

local function SaveData(Player)
  local Data = {}
  for _, Values in pairs(Player.Inventory:GetChildren()) do
    table.insert(Data, {Values.Name, Values.Value})
  end
  DataStore:SetAsync(Plr.UserId, Data)
end

Players.PlayerAdded:Connect(OnPlayerAdded)
Players.PlayerRemoving:Connect(SaveData)

game.BindToClose:Connect(function()
  for _, Player in pairs(Players:GetPlayers()) do
    SaveData(Player)
  end
  wait(10)
end)

I would change the game.BindToClose() function to 3 seconds instead of 10. 10 is a little too long.

The wait(10) doesn’t serve any purpose, I’m not sure why it’s even there.

1 Like