Loading...
Script reference
Everything your scripts can do, with examples to copy.
Light, particles and time of day
Money counter (leaderstats)
Put this Script in ServerScriptService. Values in a folder named leaderstats appear in the list at the top right, and the server keeps them.
game.Players.PlayerAdded:Connect(function(player) local stats = Instance.new("Folder") stats.Name = "leaderstats" stats.Parent = player local money = Instance.new("IntValue") money.Name = "Money" money.Parent = stats while player.Parent do wait(1) money.Value += 10 end end)
Showing money in a GUI
Put this LocalScript inside a TextLabel in StarterGui. It updates the label every time the server changes the money.
local player = game.Players.LocalPlayer local money = player:WaitForChild("leaderstats"):WaitForChild("Money") local label = script.Parent local function show() label.Text = "Money: " .. money.Value end show() money.Changed:Connect(show)
Counting from 1 to 10 in a GUI
A LocalScript inside a TextLabel can change its text at any time.
local label = script.Parent for number = 1, 10 do label.Text = number wait(1) end
Playing an animation
Make it in Studio: Avatar tab, Animation Editor. Copy its ID there and load it through the Animator of a character.
local animation = Instance.new("Animation") animation.AnimationId = "assetid://your-id" local player = game.Players.LocalPlayer local humanoid = (player.Character or player.CharacterAdded:Wait()):WaitForChild("Humanoid") humanoid:WaitForChild("Animator"):LoadAnimation(animation):Play()
Animation tracks and events
A loaded track has Length, Looped, Speed, Priority, IsPlaying, Stopped, Ended and DidLoop. Events placed in the Animation Editor arrive through GetMarkerReachedSignal.
local animation = script.Parent.Hit local humanoid = game.Players.LocalPlayer.Character:WaitForChild('Humanoid') local track = humanoid:WaitForChild('Animator'):LoadAnimation(animation) track:GetMarkerReachedSignal('Swing'):Connect(function(value) print('Marker reached', value) end) track.Stopped:Connect(function() print('Finished after', track.Length, 'seconds') end) track:Play() track:AdjustSpeed(1.5)
Lighting
Time of day, brightness and fog of the whole game. Click Lighting in the Explorer to set it, or change it from a script.
local lighting = game:GetService("Lighting") lighting.ClockTime = 20 lighting.FogEnd = 150
PointLight and SpotLight
Put them inside a part. A PointLight shines in all directions, a SpotLight towards one face.
local light = Instance.new("PointLight") light.Color = Color3.fromRGB(255, 200, 120) light.Range = 24 light.Parent = workspace.Part
ParticleEmitter
Shoots small images out of a part. Emit releases a burst at once.
local emitter = Instance.new("ParticleEmitter") emitter.Rate = 40 emitter.Lifetime = NumberRange.new(1, 2) emitter.Color = ColorSequence.new(Color3.new(1, 1, 0), Color3.new(1, 0, 0)) emitter.Parent = workspace.Part emitter:Emit(50)
Fire, Smoke and Sparkles
Ready-made effects: one line and the part burns.
Instance.new("Fire", workspace.Part) Instance.new("Smoke", workspace.Part)
BillboardGui
A GUI that floats over a part and always faces the camera.
local sign = Instance.new("BillboardGui") sign.Size = UDim2.new(0, 200, 0, 50) sign.StudsOffset = Vector3.new(0, 3, 0) sign.Parent = workspace.Part local text = Instance.new("TextLabel") text.Size = UDim2.new(1, 0, 1, 0) text.Text = "Shop" text.Parent = sign
The kinds of scripts
Script
Runs on the server, once for the whole game. It decides what really happens: damage, coins, saving. Put it in ServerScriptService or inside a part.
print("I run on the server")
LocalScript
Runs on one player's device. It handles that player's screen, keys and buttons. Put it in StarterPlayerScripts or inside a GUI object.
print("Hello " .. game.Players.LocalPlayer.Name)
RemoteEvent
The bridge between LocalScript and Script. Lives in ReplicatedStorage. Never trust what a player sends: check it on the server.
-- LocalScript game.ReplicatedStorage.RemoteEvent:FireServer("hello") -- Script game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function(player, text) print(player.Name, text) end)
ModuleScript
Code that several scripts share. It runs once, when it is first required, and must end with return. In ReplicatedStorage both sides can use it, in ServerScriptService only the server.
-- ModuleScript named Coins in ReplicatedStorage local Coins = {} function Coins.double(n) return n * 2 end return Coins -- Then, in any Script: -- local Coins = require(game.ReplicatedStorage.Coins) -- print(Coins.double(21))
ServerStorage and ReplicatedStorage
Objects in these services are not visible in the world. Keep templates there and Clone them. Players cannot see what is in ServerStorage.
local coin = game.ServerStorage.Coin:Clone() coin.Position = Vector3.new(0, 5, 0) coin.Parent = workspace
BindableEvent
Lets scripts on the same side talk to each other.
local event = Instance.new("BindableEvent") event.Event:Connect(function(text) print(text) end) event:Fire("hello")
Finding and creating objects
Instance.new
Creates a new object, for example a Part, Folder or Sound.
local part = Instance.new("Part") part.Anchored = true part.Position = Vector3.new(0, 10, 0) part.Parent = workspace
FindFirstChild
Looks for a child by name and returns nil if there is none, so your script does not crash.
local door = workspace:FindFirstChild("Door") if door then door.Transparency = 0.5 end
WaitForChild
Waits until a child exists. Useful in LocalScripts, where things arrive a little later.
local remote = game.ReplicatedStorage:WaitForChild("RemoteEvent")
GetChildren and GetDescendants
GetChildren lists direct children, GetDescendants everything below an object.
for _, child in ipairs(workspace:GetChildren()) do print(child.Name) end
Clone and Destroy
Clone makes a copy, Destroy removes an object for good.
local copy = workspace.Part:Clone() copy.Parent = workspace wait(5) copy:Destroy()
IsA
Checks the kind of an object.
if workspace.Part:IsA("Part") then print("It is a part") end
Attributes
Store your own values on any object.
workspace.Part:SetAttribute("Damage", 10) print(workspace.Part:GetAttribute("Damage"))
Values
IntValue, NumberValue, StringValue and BoolValue hold one value and fire Changed.
local score = Instance.new("IntValue") score.Changed:Connect(function(value) print(value) end) score.Value = 5
Values you use often
Vector3
A position or size with X, Y and Z. Vectors can be added and multiplied.
local up = workspace.Part.Position + Vector3.new(0, 5, 0) print(up.Magnitude)
CFrame
Position and rotation together. CFrame.Angles uses radians.
workspace.Part.CFrame = CFrame.new(0, 10, 0) * CFrame.Angles(0, math.rad(45), 0)
Color3 and BrickColor
Color3 sets exact colors, BrickColor uses color names.
workspace.Part.Color = Color3.fromRGB(255, 120, 0) workspace.Part.BrickColor = BrickColor.new("Really red")
UDim2
Position and size of GUI objects: share of the screen and pixels for X and Y.
script.Parent.Position = UDim2.new(0.5, 0, 0, 20)
Enum
Fixed lists of options, such as keys and materials.
workspace.Part.Material = Enum.Material.Neon
Events
Connect, Once and Wait
Connect runs a function every time, Once only the first time, and Wait pauses until it happens.
local connection = workspace.Part.Touched:Connect(function(hit) print(hit.Name) end) wait(10) connection:Disconnect()
Touched
Fires when something touches a part. Used for lava, coins and teleporters.
workspace.Part.Touched:Connect(function(hit) print(hit.Parent.Name) end)
ClickDetector
Makes a 3D part clickable.
local detector = Instance.new("ClickDetector", workspace.Part) detector.MouseClick:Connect(function(player) print(player.Name) end)
PlayerAdded and PlayerRemoving
Fire when players join and leave. Used for loading and saving.
game.Players.PlayerAdded:Connect(function(player) print(player.Name .. " joined") end)
Humanoid
Controls a character: Health, WalkSpeed, JumpPower, TakeDamage and the Died event.
local humanoid = game.Players.LocalPlayer.Character:WaitForChild("Humanoid") humanoid.WalkSpeed = 24 humanoid.Died:Connect(function() print("Oh no") end)
MouseButton1Click
Fires when a TextButton is clicked.
script.Parent.MouseButton1Click:Connect(function() print("Clicked") end)
Time
wait
Pauses a script for some seconds. Every endless loop needs one.
while true do print("tick") wait(1) end
task.spawn and task.delay
Runs code at the same time as the rest, or a bit later.
task.spawn(function() print("now") end) task.delay(2, function() print("2 seconds later") end)
Services
Players
Knows all players. LocalPlayer is you, in a LocalScript.
for _, player in ipairs(game.Players:GetPlayers()) do print(player.Name) end
RunService
Heartbeat fires every frame, for smooth movement.
game:GetService("RunService").Heartbeat:Connect(function(dt) workspace.Part.Position = workspace.Part.Position + Vector3.new(dt, 0, 0) end)
UserInputService
Keyboard input, in a LocalScript.
local input = game:GetService("UserInputService") print(input:IsKeyDown(Enum.KeyCode.W))
TweenService
Moves, fades or colors things smoothly over time.
local info = TweenInfo.new(2) local tween = game:GetService("TweenService"):Create(workspace.Part, info, { Transparency = 1 }) tween:Play() tween.Completed:Wait()
DataStoreService
Saves data between sessions. Only in Scripts.
local store = game:GetService("DataStoreService"):GetDataStore("Coins") store:SetAsync("somebody", 5) print(store:GetAsync("somebody"))
Debris
Removes an object after some time, without blocking.
game:GetService("Debris"):AddItem(workspace.Part, 5)
CollectionService
Gives objects tags, so one script can handle all lava parts at once.
local tags = game:GetService("CollectionService") tags:AddTag(workspace.Part, "Lava") for _, part in ipairs(tags:GetTagged("Lava")) do print(part.Name) end
MarketplaceService
Sells passes and checks whether a player owns one.
local market = game:GetService("MarketplaceService") local player = game.Players.LocalPlayer market:PromptGamePassPurchase(player, "PASS-ID")
MarketplaceService: products
Products are bought again and again. ProcessReceipt runs on the server once for every purchase.
local market = game:GetService("MarketplaceService") market.ProcessReceipt = function(info) local player = game.Players:GetPlayerByUserId(info.PlayerId) if player and info.ProductId == "PRODUCT-ID" then player.leaderstats.Coins.Value += 500 end return Enum.ProductPurchaseDecision.PurchaseGranted end
MarketplaceService: bought just now
Gives the bonus of a pass right after buying it, without rejoining.
local market = game:GetService("MarketplaceService") market.PromptGamePassPurchaseFinished:Connect(function(player, passId, bought) if bought and passId == "PASS-ID" then player.Character.Humanoid.WalkSpeed = 28 end end)
BadgeService
Awards badges to players.
game:GetService("BadgeService"):AwardBadge(12345, "BADGE-ID")
Sound
Plays audio: your own file or the free library (flinzu:coin, flinzu:music-happy ...). Play, Pause, Resume, Stop, Volume, Looped, PlaybackSpeed, and in LocalScripts the Ended event.
local sound = Instance.new("Sound", workspace) sound.SoundId = "flinzu:music-adventure" sound.Looped = true sound.Volume = 0.4 sound:Play()
Tool
Something players hold: put it in StarterPack, give it a part called Handle. Equipped, Unequipped, Activated (click) and Deactivated. Humanoid:EquipTool and UnequipTools move it in and out of the hand.
local tool = script.Parent tool.Activated:Connect(function() print(tool.Parent.Name .. " used " .. tool.Name) end)
ProximityPrompt
Shows "Press E" near a part. ActionText, ObjectText, KeyboardKeyCode, HoldDuration, MaxActivationDistance and Enabled. Triggered, PromptButtonHoldBegan and PromptButtonHoldEnded fire on the server.
local prompt = Instance.new("ProximityPrompt", workspace.Chest) prompt.ActionText = "Open" prompt.KeyboardKeyCode = Enum.KeyCode.F prompt.Triggered:Connect(function(player) print(player.Name .. " opened the chest") prompt.Enabled = false end)
Looking around the world
workspace:Raycast
Shoots an invisible line and tells you what it hits. Used for guns, ground checks and line of sight. Rotated parts count as unrotated.
local hit = workspace:Raycast(Vector3.new(0, 50, 0), Vector3.new(0, -100, 0)) if hit then print(hit.Instance.Name, hit.Position, hit.Distance) end
RaycastParams
Makes a ray ignore objects, or only see certain ones.
local params = RaycastParams.new() params.FilterDescendantsInstances = { workspace.Part } print(workspace:Raycast(Vector3.new(0, 50, 0), Vector3.new(0, -100, 0), params))
PivotTo
Moves a whole Model at once.
workspace.Model:PivotTo(CFrame.new(0, 20, 0))
Ready-made scripts
Lava part
Put it inside a part. Anyone touching the part dies.
local part = script.Parent part.Touched:Connect(function(hit) local humanoid = hit.Parent:FindFirstChild("Humanoid") if humanoid then humanoid.Health = 0 end end)
Healing part
Put it inside a part. It restores health, at most once per second.
local part = script.Parent local ready = true part.Touched:Connect(function(hit) local humanoid = hit.Parent:FindFirstChild("Humanoid") if humanoid and ready then ready = false humanoid.Health = math.min(humanoid.MaxHealth, humanoid.Health + 25) wait(1) ready = true end end)
Speed boost
Put it inside a part. Touching it makes the player fast for 5 seconds.
local part = script.Parent local boosted = {} part.Touched:Connect(function(hit) local humanoid = hit.Parent:FindFirstChild("Humanoid") if humanoid and not boosted[humanoid] then boosted[humanoid] = true humanoid.WalkSpeed = 40 wait(5) humanoid.WalkSpeed = 16 boosted[humanoid] = nil end end)
Click door
Put it inside a part. A click opens or closes it.
local door = script.Parent local detector = Instance.new("ClickDetector", door) local open = false detector.MouseClick:Connect(function() open = not open door.CanCollide = not open door.Transparency = open and 0.7 or 0 end)
Moving platform
Put it inside an anchored part. It glides back and forth forever.
local TweenService = game:GetService("TweenService") local part = script.Parent local info = TweenInfo.new(3, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, -1, true) local goal = { Position = part.Position + Vector3.new(20, 0, 0) } TweenService:Create(part, info, goal):Play()
Spinning part
Put it inside an anchored part. It turns all the time.
local RunService = game:GetService("RunService") local part = script.Parent RunService.Heartbeat:Connect(function(dt) part.CFrame = part.CFrame * CFrame.Angles(0, math.rad(90) * dt, 0) end)
Teleporter
Put it inside a part and name another part Target. Touching teleports the player there.
local part = script.Parent part.Touched:Connect(function(hit) local target = workspace:FindFirstChild("Target") local character = hit.Parent if target and character:FindFirstChild("Humanoid") then character:MoveTo(target.Position + Vector3.new(0, 3, 0)) end end)
Collectable coin
Put it inside a part. It counts a coin for the player and comes back after 5 seconds.
local Players = game:GetService("Players") local coin = script.Parent local taken = false coin.Touched:Connect(function(hit) local player = Players:GetPlayerFromCharacter(hit.Parent) if player and not taken then taken = true player:SetAttribute("Coins", (player:GetAttribute("Coins") or 0) + 1) print(player.Name, "has", player:GetAttribute("Coins"), "coins") coin.Transparency = 1 wait(5) coin.Transparency = 0 taken = false end end)
Save player data
Put it in ServerScriptService. Coins are loaded on joining and saved on leaving.
local Players = game:GetService("Players") local store = game:GetService("DataStoreService"):GetDataStore("Coins") Players.PlayerAdded:Connect(function(player) player:SetAttribute("Coins", store:GetAsync(player.UserId) or 0) end) Players.PlayerRemoving:Connect(function(player) store:SetAsync(player.UserId, player:GetAttribute("Coins") or 0) end)
Round timer
Put it in ServerScriptService. It repeats a break and a round; add your own game code.
local BREAK_TIME = 10 local ROUND_TIME = 60 while true do print("Break: " .. BREAK_TIME .. " seconds") wait(BREAK_TIME) print("The round starts!") wait(ROUND_TIME) print("The round is over!") end
GUI button
Put it inside a TextButton. It reacts to clicks.
local button = script.Parent button.MouseButton1Click:Connect(function() button.Text = "Clicked!" end)
Key press
Put it in StarterPlayerScripts. It reacts when the player presses E.
local UserInputService = game:GetService("UserInputService") UserInputService.InputBegan:Connect(function(input) if input.KeyCode == Enum.KeyCode.E then print("E was pressed") end end)
Listen to a RemoteEvent
Needs a RemoteEvent called RemoteEvent in ReplicatedStorage. A LocalScript calls FireServer.
local remote = game.ReplicatedStorage:WaitForChild("RemoteEvent") remote.OnServerEvent:Connect(function(player, message) print(player.Name, "says", message) end)