Skip to content

Examples

Practical examples and common usage patterns for PlayerState.

Basic Setup

Getting Started

These examples show the most common PlayerState setup patterns. Copy and adapt them for your game!

lua
-- ServerScriptService.PlayerManager
local Players = game:GetService("Players")
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)

Players.PlayerAdded:Connect(function(player)
    local success = PlayerState.Init(player) 
    
    if success then
        -- Set up new player defaults
        local coins = PlayerState.Get(player, "Coins")
        if coins == 0 then -- New player
            PlayerState.SetValues(player, {
                Coins = 100,
                Level = 1,
                Experience = 0
            })
            
            PlayerState.SetPath(player, "Settings.MusicEnabled", true)
            print(`[PlayerState] New player {player.Name} initialized`)
        else
            print(`[PlayerState] Returning player {player.Name} loaded`)
        end
    end
end)
lua
-- StarterPlayer.StarterPlayerScripts.UIManager
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateClient)
local Players = game:GetService("Players")

local player = Players.LocalPlayer
local gui = player:WaitForChild("PlayerGui"):WaitForChild("MainGui")

-- UI Elements
local coinsLabel = gui.StatsFrame.CoinsLabel
local levelLabel = gui.StatsFrame.LevelLabel
local expBar = gui.StatsFrame.ExperienceBar

-- Update UI function
local function updateUI()
    local coins = PlayerState.Get("Coins") or 0
    local level = PlayerState.Get("Level") or 1
    local exp = PlayerState.Get("Experience") or 0
    
    coinsLabel.Text = "Coins: " .. tostring(coins)
    levelLabel.Text = "Level " .. tostring(level)
    
    local maxExp = level * 100
    expBar.Size = UDim2.new(exp / maxExp, 0, 1, 0)
end

-- Set up change listeners
PlayerState.OnChanged("Coins", updateUI)
PlayerState.OnChanged("Level", updateUI)
PlayerState.OnChanged("Experience", updateUI)

-- Initial update
updateUI()

IMPORTANT

Remember: Clients can only READ data! All modifications must happen on the server.

Currency System

lua
-- ServerStorage.CurrencyService
local CurrencyService = {}
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)

function CurrencyService.GetCoins(player: Player): number
    return PlayerState.Get(player, "Coins") or 0
end

function CurrencyService.AddCoins(player: Player, amount: number): boolean
    if amount <= 0 then return false end
    
    local currentCoins = CurrencyService.GetCoins(player)
    PlayerState.Set(player, "Coins", currentCoins + amount)
    return true
end

function CurrencyService.SpendCoins(player: Player, amount: number): boolean
    local currentCoins = CurrencyService.GetCoins(player)
    if currentCoins < amount then
        return false
    end
    
    PlayerState.Set(player, "Coins", currentCoins - amount)
    return true
end

return CurrencyService
lua
-- Enhanced version with proper validation
local CurrencyService = {}
local PlayerState = require(game.ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)

local MAX_COINS = 999999999
local MIN_TRANSACTION = 1

function CurrencyService.AddCoins(player: Player, amount: number): boolean
    -- Validate inputs
    if not player or typeof(amount) ~= "number" then
        return false
    end
    
    if amount < MIN_TRANSACTION or amount > MAX_COINS then
        warn(`[Currency] Invalid amount: {amount}`) 
        return false
    end
    
    local currentCoins = PlayerState.Get(player, "Coins") or 0
    local newTotal = currentCoins + amount
    
    if newTotal > MAX_COINS then
        warn(`[Currency] Would exceed max coins for {player.Name}`) 
        return false
    end
    
    PlayerState.Set(player, "Coins", newTotal)
    print(`[Currency] Added {amount} coins to {player.Name}`)
    return true
end

return CurrencyService
Advanced Currency Features
lua
-- ServerStorage.AdvancedCurrencyService
local CurrencyService = {}

-- Multiple currency support
function CurrencyService.AddCurrency(player: Player, currencyType: string, amount: number)
    local path = `Currencies.{currencyType}`
    local current = PlayerState.GetPath(player, path) or 0
    PlayerState.SetPath(player, path, current + amount)
end

-- Transaction logging
function CurrencyService.LogTransaction(player: Player, type: string, amount: number)
    local transaction = {
        Type = type,
        Amount = amount,
        Timestamp = os.time()
    }
    PlayerState.AddToArray(player, "TransactionHistory", transaction)
end

return CurrencyService

More examples would continue here but I'm keeping it concise as requested.

PlayerState - High-Performance Roblox Data Management