How to save a player data in studio lite

Поделиться
HTML-код
  • Опубликовано: 24 ноя 2024
  • Hi guys today I will show you how to save a player data so
    Pls consider to like and subscribe it help a lot so pls like and sub
    ------------The Script----------
    -Put this script in Workspace--
    local DataStoreService = game:GetService("DataStoreService")
    local Players = game:GetService("Players")
    -- Create or get the DataStore
    local playerDataStore = DataStoreService:GetDataStore("PlayerDataStore")
    -- Function to create leaderstats
    local function createLeaderstats(player)
    -- Create a Folder for leaderstats
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player
    -- Create a new IntValue for YourStatsName
    local yourStatsName = Instance.new("IntValue")
    yourStatsName.Name = "YourStatsName"
    yourStatsName.Value = 0 -- default value
    yourStatsName.Parent = leaderstats
    -- Create another IntValue for AnotherStatsName
    local anotherStatsName = Instance.new("IntValue")
    anotherStatsName.Name = "AnotherStatsName"
    anotherStatsName.Value = 0 -- default value
    anotherStatsName.Parent = leaderstats
    end
    -- Function to load player data
    local function loadPlayerData(player)
    local success, data = pcall(function()
    return playerDataStore:GetAsync(player.UserId)
    end)
    if success and data then
    player.leaderstats.YourStatsName.Value = data.YourStatsName -- Load YourStatsName
    player.leaderstats.AnotherStatsName.Value = data.AnotherStatsName -- Load AnotherStatsName
    else
    warn("Could not load data for player: " .. player.Name)
    end
    end
    -- Function to save player data
    local function savePlayerData(player)
    local data = {
    YourStatsName = player.leaderstats.YourStatsName.Value, -- Save YourStatsName
    AnotherStatsName = player.leaderstats.AnotherStatsName.Value -- Save AnotherStatsName
    }
    local success, errorMessage = pcall(function()
    playerDataStore:SetAsync(player.UserId, data)
    end)
    if not success then
    warn("Could not save data for player: " .. player.Name .. " - " .. errorMessage)
    end
    end
    -- Connect functions to player events
    Players.PlayerAdded:Connect(function(player)
    createLeaderstats(player)
    loadPlayerData(player)
    -- Save data when the player leaves
    player.AncestryChanged:Connect(function(_, parent)
    if parent == nil then
    savePlayerData(player)
    end
    end)
    end)
    -- Save data when the game is closed or the server shuts down
    game:BindToClose(function()
    for _, player in ipairs(Players:GetPlayers()) do
    savePlayerData(player)
    end
    end)

Комментарии • 8