<div> <h1>StudioVault - Free Roblox Luau Scripts</h1> <p>Free copy-paste Luau scripts for Roblox Studio developers. 25 scripts across 12 categories.</p> <article><h2>Leaderstats Setup</h2><p>Create a leaderboard with Cash and Level values that appear above every player's head.</p><p>Category: Leaderstats | Difficulty: Beginner | Placement: ServerScriptService</p></article><article><h2>DataStore: Save & Load</h2><p>Persist player data across sessions with error handling and an auto-save loop.</p><p>Category: Datastores | Difficulty: Intermediate | Placement: ServerScriptService</p></article><article><h2>Gamepass Check</h2><p>Check if a player owns a gamepass on join and grant a perk or reward.</p><p>Category: Gamepasses | Difficulty: Intermediate | Placement: ServerScriptService</p></article><article><h2>Kill Brick</h2><p>A part that kills any player who touches it. Perfect for lava, voids, and traps.</p><p>Category: Parts & Doors | Difficulty: Beginner | Placement: Script inside Part</p></article><article><h2>Proximity Prompt Door</h2><p>Door that opens and closes on interact with a smooth TweenService animation.</p><p>Category: Parts & Doors | Difficulty: Intermediate | Placement: Script inside Door Model</p></article><article><h2>Give Tool on Touch</h2><p>Give a player a tool from ServerStorage when they step on a part.</p><p>Category: Tools | Difficulty: Beginner | Placement: Script inside Part</p></article><article><h2>Basic Round System</h2><p>Loop-based round system with intermission, random map selection, and countdown timer.</p><p>Category: Systems | Difficulty: Intermediate | Placement: ServerScriptService</p></article><article><h2>Checkpoint System</h2><p>Save a player's respawn location when they touch a checkpoint.</p><p>Category: Systems | Difficulty: Beginner | Placement: Script inside Checkpoint Part</p></article><article><h2>RemoteEvent: Client to Server</h2><p>Safe template for client-to-server communication with server-side validation.</p><p>Category: Networking | Difficulty: Intermediate | Placement: ServerScriptService + LocalScript</p></article><article><h2>Admin Commands</h2><p>Chat-based admin: /kick, /speed, /heal, /respawn with partial name matching.</p><p>Category: Admin | Difficulty: Intermediate | Placement: ServerScriptService</p></article><article><h2>Shop System</h2><p>Buy items with in-game cash via RemoteEvent. Server validates every purchase.</p><p>Category: Economy | Difficulty: Intermediate | Placement: ServerScriptService + LocalScript</p></article><article><h2>NPC Typewriter Dialogue</h2><p>Display NPC dialogue with a classic typewriter effect.</p><p>Category: NPC | Difficulty: Intermediate | Placement: LocalScript in StarterPlayerScripts</p></article><article><h2>NPC Wander (Pathfinding)</h2><p>NPC that randomly wanders using PathfindingService with jump support.</p><p>Category: NPC | Difficulty: Intermediate | Placement: Script inside NPC Model</p></article><article><h2>Give Cash on Kill</h2><p>Award the killer cash when they eliminate another player.</p><p>Category: Economy | Difficulty: Beginner | Placement: ServerScriptService</p></article><article><h2>Day/Night Cycle</h2><p>Smooth looping day/night cycle with configurable speed and start time.</p><p>Category: Systems | Difficulty: Beginner | Placement: ServerScriptService</p></article><article><h2>GUI Slide-in Tween</h2><p>Animate a Frame sliding on and off screen. Great for menus and panels.</p><p>Category: GUI | Difficulty: Beginner | Placement: LocalScript in StarterGui</p></article><article><h2>Toast Notification</h2><p>Pop-up toast that slides in from the bottom and auto-dismisses.</p><p>Category: GUI | Difficulty: Intermediate | Placement: LocalScript in StarterGui</p></article><article><h2>Anti-Cheat Speed Detection</h2><p>Detect and kick players moving faster than a configurable threshold.</p><p>Category: Security | Difficulty: Intermediate | Placement: ServerScriptService</p></article><article><h2>RemoteFunction: Get Server Data</h2><p>Client requests data from server synchronously with server-side validation.</p><p>Category: Networking | Difficulty: Intermediate | Placement: ServerScriptService + LocalScript</p></article><article><h2>Mobile Action Button</h2><p>On-screen button that only renders on touch devices.</p><p>Category: GUI | Difficulty: Beginner | Placement: LocalScript in StarterGui</p></article><article><h2>Teleport to Place</h2><p>Teleport a player to another Roblox Place ID. Works for portals and multiplace games.</p><p>Category: Systems | Difficulty: Beginner | Placement: Script inside Part</p></article><article><h2>Team System</h2><p>Assign players to teams on join with auto-balancing.</p><p>Category: Systems | Difficulty: Intermediate | Placement: ServerScriptService</p></article><article><h2>Tycoon Conveyor Belt</h2><p>A moving conveyor belt that pushes parts or players. Classic tycoon mechanic.</p><p>Category: Parts & Doors | Difficulty: Beginner | Placement: Script inside Conveyor Part</p></article><article><h2>Inventory System</h2><p>Server-side inventory using a table. Add, remove, and check items.</p><p>Category: Economy | Difficulty: Intermediate | Placement: ServerScriptService</p></article><article><h2>Music Player</h2><p>Plays a playlist of songs in order using SoundService. Loops automatically.</p><p>Category: Systems | Difficulty: Beginner | Placement: ServerScriptService</p></article> </div>
Free for all Roblox developers

The Script Vault
for Roblox Devs

Copy-paste ready Luau scripts for the most common Roblox Studio tasks. No fluff, no broken tutorials.

πŸ”
25
Scripts
12
Categories
Free
Always
Filter by category
25 scripts
LeaderstatsBeginner
ServerScriptService
Leaderstats Setup
Create a leaderboard with Cash and Level values that appear above every player's head.
View Page β†’
-- Leaderstats Setup
-- Place in ServerScriptService

game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local cash = Instance.new("IntValue")
    cash.Name = "Cash"
    cash.Value = 0
    cash.Parent = leaderstats

    local level = Instance.new("IntValue")
    level.Name = "Level"
    level.Value = 1
    level.Parent = leaderstats
end)
DatastoresIntermediate
ServerScriptService
DataStore: Save & Load
Persist player data across sessions with error handling and an auto-save loop.
View Page β†’
-- DataStore: Save & Load Player Data
-- Place in ServerScriptService

local DataStoreService = game:GetService("DataStoreService")
local db = DataStoreService:GetDataStore("PlayerData_v1")

game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local cash = Instance.new("IntValue")
    cash.Name = "Cash"
    cash.Parent = leaderstats

    local ok, data = pcall(function()
        return db:GetAsync(player.UserId)
    end)
    if ok and data then cash.Value = data.Cash or 0 end
end)

game.Players.PlayerRemoving:Connect(function(player)
    local cash = player.leaderstats.Cash.Value
    pcall(function() db:SetAsync(player.UserId, { Cash = cash }) end)
end)

task.spawn(function()
    while task.wait(60) do
        for _, p in ipairs(game.Players:GetPlayers()) do
            local cash = p.leaderstats and p.leaderstats.Cash
            if cash then
                pcall(function() db:SetAsync(p.UserId, { Cash = cash.Value }) end)
            end
        end
    end
end)
GamepassesIntermediate
ServerScriptService
Gamepass Check
Check if a player owns a gamepass on join and grant a perk or reward.
View Page β†’
-- Gamepass Ownership Check
-- Place in ServerScriptService

local MarketplaceService = game:GetService("MarketplaceService")
local GAMEPASS_ID = 000000

game.Players.PlayerAdded:Connect(function(player)
    local ok, hasPass = pcall(function()
        return MarketplaceService:UserOwnsGamePassAsync(player.UserId, GAMEPASS_ID)
    end)
    if ok and hasPass then
        player.CharacterAdded:Connect(function(char)
            local hum = char:WaitForChild("Humanoid")
            hum.WalkSpeed = 32
        end)
    end
end)
Parts & DoorsBeginner
Script inside Part
Kill Brick
A part that kills any player who touches it. Perfect for lava, voids, and traps.
View Page β†’
-- Kill Brick
-- Place a Script inside the Part

local part = script.Parent

part.Touched:Connect(function(hit)
    local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid")
    if humanoid and humanoid.Health > 0 then
        humanoid.Health = 0
    end
end)
Parts & DoorsIntermediate
Script inside Door Model
Proximity Prompt Door
Door that opens and closes on interact with a smooth TweenService animation.
View Page β†’
-- Proximity Prompt Door
local TweenService = game:GetService("TweenService")
local door   = script.Parent
local prompt = door:FindFirstChildOfClass("ProximityPrompt", true)
local isOpen = false
local debounce = false
local closedCF = door.PrimaryPart.CFrame

prompt.Triggered:Connect(function()
    if debounce then return end
    debounce = true
    isOpen = not isOpen
    TweenService:Create(
        door.PrimaryPart,
        TweenInfo.new(0.4, Enum.EasingStyle.Quad),
        { CFrame = isOpen and closedCF * CFrame.Angles(0, math.rad(90), 0) or closedCF }
    ):Play()
    prompt.ActionText = isOpen and "Close" or "Open"
    task.wait(0.5)
    debounce = false
end)
ToolsBeginner
Script inside Part
Give Tool on Touch
Give a player a tool from ServerStorage when they step on a part.
View Page β†’
-- Give Tool on Touch
local ServerStorage = game:GetService("ServerStorage")
local TOOL_NAME = "Sword"
local debounces = {}

script.Parent.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if not player or debounces[player.UserId] then return end
    debounces[player.UserId] = true
    local tool = ServerStorage:FindFirstChild(TOOL_NAME)
    if tool and not player.Backpack:FindFirstChild(TOOL_NAME)
       and not hit.Parent:FindFirstChild(TOOL_NAME) then
        tool:Clone().Parent = player.Backpack
    end
    task.wait(1)
    debounces[player.UserId] = nil
end)
SystemsIntermediate
ServerScriptService
Basic Round System
Loop-based round system with intermission, random map selection, and countdown timer.
View Page β†’
-- Basic Round System
local ROUND_TIME   = 120
local INTERMISSION = 15
local MIN_PLAYERS  = 2
local mapsFolder   = workspace:WaitForChild("Maps")
local activeMap    = nil

local function loadMap()
    if activeMap then activeMap:Destroy() end
    local maps = mapsFolder:GetChildren()
    if #maps == 0 then return end
    activeMap = maps[math.random(1, #maps)]:Clone()
    activeMap.Parent = workspace
end

local function countdown(seconds, label)
    for i = seconds, 1, -1 do
        print(label .. i)
        task.wait(1)
    end
end

while true do
    repeat task.wait(2) until #game.Players:GetPlayers() >= MIN_PLAYERS
    countdown(INTERMISSION, "Intermission: ")
    loadMap()
    countdown(ROUND_TIME, "Time left: ")
    if activeMap then activeMap:Destroy(); activeMap = nil end
    task.wait(2)
end
SystemsBeginner
Script inside Checkpoint Part
Checkpoint System
Save a player's respawn location when they touch a checkpoint.
View Page β†’
-- Checkpoint System
local checkpoint = script.Parent
local debounces  = {}

checkpoint.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if not player or debounces[player.UserId] then return end
    debounces[player.UserId] = true
    if player.RespawnLocation ~= checkpoint then
        player.RespawnLocation = checkpoint
        local orig = checkpoint.Color
        checkpoint.Color = Color3.fromRGB(80, 227, 164)
        task.wait(0.4)
        checkpoint.Color = orig
    end
    task.wait(1)
    debounces[player.UserId] = nil
end)
NetworkingIntermediate
ServerScriptService + LocalScript
RemoteEvent: Client to Server
Safe template for client-to-server communication with server-side validation.
View Page β†’
-- RemoteEvent: Client to Server
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local myEvent = Instance.new("RemoteEvent")
myEvent.Name = "MyEvent"
myEvent.Parent = ReplicatedStorage

myEvent.OnServerEvent:Connect(function(player, action, value)
    if typeof(action) ~= "string" then return end
    if typeof(value)  ~= "number"  then return end
    if action == "BuyItem" then
        local cash = player.leaderstats and player.leaderstats.Cash
        if cash and cash.Value >= value then
            cash.Value -= value
        end
    end
end)

-- CLIENT LocalScript:
-- local myEvent = ReplicatedStorage:WaitForChild("MyEvent")
-- myEvent:FireServer("BuyItem", 50)
AdminIntermediate
ServerScriptService
Admin Commands
Chat-based admin: /kick, /speed, /heal, /respawn with partial name matching.
View Page β†’
-- Admin Commands
local ADMINS = { [000000000] = true }

local function findPlayer(name)
    for _, p in ipairs(game.Players:GetPlayers()) do
        if p.Name:lower():sub(1, #name) == name:lower() then return p end
    end
end

game.Players.PlayerAdded:Connect(function(player)
    if not ADMINS[player.UserId] then return end
    player.Chatted:Connect(function(msg)
        local args = msg:split(" ")
        local cmd, target = args[1]:lower(), args[2] and findPlayer(args[2])
        if cmd == "/kick" and target then
            target:Kick(args[3] or "Kicked by admin.")
        elseif cmd == "/speed" and target and args[3] then
            local hum = target.Character and target.Character:FindFirstChildOfClass("Humanoid")
            if hum then hum.WalkSpeed = tonumber(args[3]) or 16 end
        elseif cmd == "/heal" and target then
            local hum = target.Character and target.Character:FindFirstChildOfClass("Humanoid")
            if hum then hum.Health = hum.MaxHealth end
        elseif cmd == "/respawn" and target then
            target:LoadCharacter()
        end
    end)
end)
EconomyIntermediate
ServerScriptService + LocalScript
Shop System
Buy items with in-game cash via RemoteEvent. Server validates every purchase.
View Page β†’
-- Shop System
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage     = game:GetService("ServerStorage")
local ITEMS = {
    Sword  = { price = 50  },
    Shield = { price = 100 },
}
local buyEvent = Instance.new("RemoteEvent")
buyEvent.Name = "BuyItem"
buyEvent.Parent = ReplicatedStorage

buyEvent.OnServerEvent:Connect(function(player, itemId)
    local item = ITEMS[itemId]
    if not item then return end
    local cash = player.leaderstats and player.leaderstats:FindFirstChild("Cash")
    if not cash or cash.Value < item.price then return end
    local tool = ServerStorage:FindFirstChild(itemId)
    if not tool then return end
    cash.Value -= item.price
    tool:Clone().Parent = player.Backpack
end)

-- CLIENT: buyEvent:FireServer("Sword")
NPCIntermediate
LocalScript in StarterPlayerScripts
NPC Typewriter Dialogue
Display NPC dialogue with a classic typewriter effect.
View Page β†’
-- NPC Typewriter Dialogue
local Players = game:GetService("Players")
local player  = Players.LocalPlayer
local gui     = player.PlayerGui:WaitForChild("DialogueGui")
local frame   = gui:WaitForChild("Frame")
local label   = frame:WaitForChild("TextLabel")

local DIALOGUE   = { "Hello, traveler.", "Are you looking for the lost sword?", "Be careful out there." }
local CHAR_SPEED = 0.04
local LINE_PAUSE = 2.5
local running    = false

local function typewrite(text)
    label.Text = ""
    for i = 1, #text do
        label.Text = text:sub(1, i)
        task.wait(CHAR_SPEED)
    end
end

local function runDialogue()
    if running then return end
    running = true
    frame.Visible = true
    for _, line in ipairs(DIALOGUE) do typewrite(line); task.wait(LINE_PAUSE) end
    frame.Visible = false
    running = false
end
NPCIntermediate
Script inside NPC Model
NPC Wander (Pathfinding)
NPC that randomly wanders using PathfindingService with jump support.
View Page β†’
-- NPC Wander with PathfindingService
local PathfindingService = game:GetService("PathfindingService")
local npc      = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local root     = npc:WaitForChild("HumanoidRootPart")
local RADIUS   = 30

local function walkTo(target)
    local path = PathfindingService:CreatePath({ AgentRadius=2, AgentHeight=5 })
    local ok = pcall(function() path:ComputeAsync(root.Position, target) end)
    if not ok or path.Status ~= Enum.PathStatus.Success then return end
    for _, wp in ipairs(path:GetWaypoints()) do
        if wp.Action == Enum.PathWaypointAction.Jump then humanoid.Jump = true end
        humanoid:MoveTo(wp.Position)
        humanoid.MoveToFinished:Wait()
    end
end

while task.wait(3) do
    if humanoid.Health > 0 then
        local p = root.Position
        walkTo(Vector3.new(
            p.X + math.random(-RADIUS, RADIUS), p.Y,
            p.Z + math.random(-RADIUS, RADIUS)
        ))
    end
end
EconomyBeginner
ServerScriptService
Give Cash on Kill
Award the killer cash when they eliminate another player.
View Page β†’
-- Give Cash on Kill
local CASH_REWARD = 10

game.Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        local humanoid = character:WaitForChild("Humanoid")
        humanoid.Died:Connect(function()
            local tag = humanoid:FindFirstChild("creator")
            if not tag or not tag.Value or tag.Value == player then return end
            local cash = tag.Value.leaderstats and tag.Value.leaderstats:FindFirstChild("Cash")
            if cash then cash.Value += CASH_REWARD end
        end)
    end)
end)
SystemsBeginner
ServerScriptService
Day/Night Cycle
Smooth looping day/night cycle with configurable speed and start time.
View Page β†’
-- Day/Night Cycle
local Lighting   = game:GetService("Lighting")
local CYCLE_TIME = 600
local TICK       = 0.1
local clock      = 8

while true do
    task.wait(TICK)
    clock = clock + (24 / CYCLE_TIME) * TICK
    if clock >= 24 then clock = 0 end
    Lighting.ClockTime = clock
end
GUIBeginner
LocalScript in StarterGui
GUI Slide-in Tween
Animate a Frame sliding on and off screen. Great for menus and panels.
View Page β†’
-- GUI Slide-in / Slide-out
local TweenService = game:GetService("TweenService")
local gui        = script.Parent
local frame      = gui:WaitForChild("MenuFrame")
local openButton = gui:WaitForChild("OpenButton")
local tweenInfo  = TweenInfo.new(0.4, Enum.EasingStyle.Quint, Enum.EasingDirection.Out)
local isOpen     = false
local OPEN_POS   = UDim2.new(0.5, 0, 0.5, 0)
local CLOSED_POS = UDim2.new(0.5, 0, 1.5, 0)
frame.Position   = CLOSED_POS

openButton.MouseButton1Click:Connect(function()
    isOpen = not isOpen
    TweenService:Create(frame, tweenInfo,
        { Position = isOpen and OPEN_POS or CLOSED_POS }):Play()
end)
GUIIntermediate
LocalScript in StarterGui
Toast Notification
Pop-up toast that slides in from the bottom and auto-dismisses.
View Page β†’
-- Toast Notification β€” call showToast() from anywhere
local TweenService = game:GetService("TweenService")
local gui = script.Parent

local function showToast(message, duration)
    duration = duration or 2.5
    local screen = Instance.new("ScreenGui", gui.Parent)
    screen.ResetOnSpawn = false; screen.IgnoreGuiInset = true
    local frame = Instance.new("Frame", screen)
    frame.Size = UDim2.new(0,260,0,48); frame.AnchorPoint = Vector2.new(0.5,1)
    frame.Position = UDim2.new(0.5,0,0.92,60); frame.BackgroundColor3 = Color3.fromRGB(20,20,40)
    frame.BorderSizePixel = 0; Instance.new("UICorner",frame).CornerRadius = UDim.new(0,10)
    local label = Instance.new("TextLabel", frame)
    label.Size = UDim2.new(1,-20,1,0); label.Position = UDim2.new(0,10,0,0)
    label.BackgroundTransparency = 1; label.Text = message
    label.TextColor3 = Color3.new(1,1,1); label.TextSize = 14
    label.Font = Enum.Font.GothamMedium; label.TextXAlignment = Enum.TextXAlignment.Left
    local info = TweenInfo.new(0.3, Enum.EasingStyle.Quint)
    TweenService:Create(frame, info, {Position=UDim2.new(0.5,0,0.92,0)}):Play()
    task.wait(duration)
    local out = TweenService:Create(frame, info, {Position=UDim2.new(0.5,0,0.92,60)})
    out:Play(); out.Completed:Wait(); screen:Destroy()
end

showToast("βœ“ Item purchased!")
SecurityIntermediate
ServerScriptService
Anti-Cheat Speed Detection
Detect and kick players moving faster than a configurable threshold.
View Page β†’
-- Anti-Cheat: Speed Detection
local MAX_SPEED      = 100
local CHECK_INTERVAL = 1
local prevPos        = {}

game.Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        local root     = character:WaitForChild("HumanoidRootPart")
        local humanoid = character:WaitForChild("Humanoid")
        prevPos[player.UserId] = root.Position
        task.spawn(function()
            while character.Parent and humanoid.Health > 0 do
                task.wait(CHECK_INTERVAL)
                if not root.Parent then break end
                local dist = (root.Position - prevPos[player.UserId]).Magnitude
                if dist / CHECK_INTERVAL > MAX_SPEED then
                    player:Kick("Kicked: abnormal speed detected.")
                    return
                end
                prevPos[player.UserId] = root.Position
            end
            prevPos[player.UserId] = nil
        end)
    end)
end)
NetworkingIntermediate
ServerScriptService + LocalScript
RemoteFunction: Get Server Data
Client requests data from server synchronously with server-side validation.
View Page β†’
-- RemoteFunction: Client Requests Data
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local rf = Instance.new("RemoteFunction")
rf.Name = "GetPlayerStats"; rf.Parent = ReplicatedStorage

rf.OnServerInvoke = function(player)
    local ls = player.leaderstats
    if not ls then return {} end
    return { cash=ls.Cash and ls.Cash.Value or 0, level=ls.Level and ls.Level.Value or 1 }
end

-- CLIENT: local stats = rf:InvokeServer()
GUIBeginner
LocalScript in StarterGui
Mobile Action Button
On-screen button that only renders on touch devices.
View Page β†’
-- Mobile Action Button (touch devices only)
local UserInputService = game:GetService("UserInputService")
if not UserInputService.TouchEnabled then return end
local player    = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid  = character:WaitForChild("Humanoid")
local button    = Instance.new("TextButton", script.Parent)
button.Size = UDim2.new(0,72,0,72); button.Position = UDim2.new(1,-90,1,-100)
button.AnchorPoint = Vector2.new(0,1); button.Text = "⚑"; button.TextSize = 28
button.BackgroundColor3 = Color3.fromRGB(40,40,80); button.TextColor3 = Color3.new(1,1,1)
button.BackgroundTransparency = 0.2; button.BorderSizePixel = 0
Instance.new("UICorner", button).CornerRadius = UDim.new(1,0)
button.MouseButton1Click:Connect(function() humanoid.Jump = true end)
SystemsBeginner
Script inside Part
Teleport to Place
Teleport a player to another Roblox Place ID. Works for portals and multiplace games.
View Page β†’
-- Teleport to Place
local TeleportService = game:GetService("TeleportService")
local PLACE_ID = 0000000000
local debounces = {}

script.Parent.Touched:Connect(function(hit)
    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if not player or debounces[player.UserId] then return end
    debounces[player.UserId] = true
    local ok, err = pcall(function()
        TeleportService:Teleport(PLACE_ID, player)
    end)
    if not ok then
        warn("Teleport failed: " .. err)
        debounces[player.UserId] = nil
    end
end)
SystemsIntermediate
ServerScriptService
Team System
Assign players to teams on join with auto-balancing.
View Page β†’
-- Team System with Auto-Balance
local Teams = game:GetService("Teams")

local function getOrCreateTeam(name, color)
    local t = Teams:FindFirstChild(name)
    if t then return t end
    local team = Instance.new("Team", Teams)
    team.Name = name; team.TeamColor = BrickColor.new(color)
    team.AutoAssignable = false; return team
end

local red  = getOrCreateTeam("Red Team",  "Bright red")
local blue = getOrCreateTeam("Blue Team", "Bright blue")

local function assignTeam(player)
    player.Team = #red:GetPlayers() <= #blue:GetPlayers() and red or blue
    player.TeamColor = player.Team.TeamColor
end

game.Players.PlayerAdded:Connect(assignTeam)
game.Players.PlayerRemoving:Connect(function()
    task.wait(1)
    for _, p in ipairs(game.Players:GetPlayers()) do assignTeam(p) end
end)
Parts & DoorsBeginner
Script inside Conveyor Part
Tycoon Conveyor Belt
A moving conveyor belt that pushes parts or players. Classic tycoon mechanic.
View Page β†’
-- Tycoon Conveyor Belt
local conveyor  = script.Parent
local SPEED     = 20
local DIRECTION = Vector3.new(1, 0, 0)

conveyor.Touched:Connect(function(hit)
    if hit.Anchored then return end
    local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid")
    if humanoid then
        local root = hit.Parent:FindFirstChild("HumanoidRootPart")
        if root then root.AssemblyLinearVelocity = DIRECTION * SPEED end
        return
    end
    if hit:IsA("BasePart") then
        hit.AssemblyLinearVelocity = DIRECTION * SPEED
    end
end)
EconomyIntermediate
ServerScriptService
Inventory System
Server-side inventory using a table. Add, remove, and check items.
View Page β†’
-- Inventory System
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local inventories = {}

local getInvRF = Instance.new("RemoteFunction")
getInvRF.Name = "GetInventory"; getInvRF.Parent = ReplicatedStorage

game.Players.PlayerAdded:Connect(function(p) inventories[p.UserId] = {} end)
game.Players.PlayerRemoving:Connect(function(p) inventories[p.UserId] = nil end)

local function addItem(player, itemId, qty)
    local inv = inventories[player.UserId]; if not inv then return end
    inv[itemId] = (inv[itemId] or 0) + (qty or 1)
end

local function removeItem(player, itemId, qty)
    local inv = inventories[player.UserId]; if not inv or not inv[itemId] then return false end
    qty = qty or 1; if inv[itemId] < qty then return false end
    inv[itemId] = inv[itemId] - qty
    if inv[itemId] <= 0 then inv[itemId] = nil end
    return true
end

getInvRF.OnServerInvoke = function(player)
    return inventories[player.UserId] or {}
end
SystemsBeginner
ServerScriptService
Music Player
Plays a playlist of songs in order using SoundService. Loops automatically.
View Page β†’
-- Music Player
local SoundService = game:GetService("SoundService")
local PLAYLIST = {
    "rbxassetid://0000000001",
    "rbxassetid://0000000002",
}
local SHUFFLE = false
local currentIndex = 1
local bgm = Instance.new("Sound")
bgm.Volume = 0.5; bgm.Parent = SoundService

local function getNext()
    if SHUFFLE then return math.random(1, #PLAYLIST) end
    local n = currentIndex + 1; return n > #PLAYLIST and 1 or n
end

bgm.Ended:Connect(function() currentIndex = getNext(); bgm.SoundId = PLAYLIST[currentIndex]; bgm:Play() end)
if #PLAYLIST > 0 then bgm.SoundId = PLAYLIST[1]; bgm:Play() end