Add 10 new Roblox Lua code templates

Expanded template library from 15 to 25 templates:
- Badge Award System: Achievement badge functionality
- Inventory System: Complete item management
- Countdown Timer UI: Visual timer with color changes
- Sound/Music Manager: Background music and SFX control
- Pathfinding NPC: AI navigation using PathfindingService
- Checkpoint System: Save/respawn at checkpoints
- Team System: Auto-balanced team assignment
- Custom Chat Commands: Player emotes and actions
- Character Morphing: Appearance transformation system
- Kill Brick: Hazard parts with visual effects

Now covers all categories: beginner, gameplay, UI, tools, and advanced.
This commit is contained in:
Claude 2026-01-17 22:20:33 +00:00
parent 68c881374d
commit 6e875b147a
No known key found for this signature in database

View file

@ -526,6 +526,673 @@ Players.PlayerAdded:Connect(function(player)
end end
end) end)
end end
end)`,
},
{
id: 'badge-award',
name: 'Badge Award System',
description: 'Award badges to players for achievements',
category: 'gameplay',
code: `local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local badgeIds = {
FirstJoin = 0, -- Replace with your badge ID
KillMonster = 0,
ReachLevel10 = 0,
}
local function awardBadge(player, badgeId)
local success, hasBadge = pcall(function()
return BadgeService:UserHasBadgeAsync(player.UserId, badgeId)
end)
if success and not hasBadge then
local awarded, errorMsg = pcall(function()
BadgeService:AwardBadge(player.UserId, badgeId)
end)
if awarded then
print("Awarded badge " .. badgeId .. " to " .. player.Name)
return true
else
warn("Error awarding badge: " .. tostring(errorMsg))
end
end
return false
end
-- Example: Award badge on first join
Players.PlayerAdded:Connect(function(player)
wait(2) -- Wait for player to fully load
awardBadge(player, badgeIds.FirstJoin)
end)
-- Export function for use in other scripts
return {
awardBadge = awardBadge,
badgeIds = badgeIds
}`,
},
{
id: 'inventory-system',
name: 'Inventory System',
description: 'Complete player inventory with items and storage',
category: 'advanced',
code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local inventoryData = {}
local function createInventory(player)
inventoryData[player.UserId] = {
items = {},
maxSlots = 20
}
end
local function addItem(player, itemName, quantity)
local inventory = inventoryData[player.UserId]
if not inventory then
warn("Player inventory not found")
return false
end
-- Check if item already exists
if inventory.items[itemName] then
inventory.items[itemName] = inventory.items[itemName] + quantity
else
-- Check if inventory is full
local itemCount = 0
for _ in pairs(inventory.items) do
itemCount = itemCount + 1
end
if itemCount >= inventory.maxSlots then
return false, "Inventory full"
end
inventory.items[itemName] = quantity
end
print("Added " .. quantity .. "x " .. itemName .. " to " .. player.Name)
return true
end
local function removeItem(player, itemName, quantity)
local inventory = inventoryData[player.UserId]
if not inventory or not inventory.items[itemName] then
return false, "Item not found"
end
if inventory.items[itemName] < quantity then
return false, "Not enough items"
end
inventory.items[itemName] = inventory.items[itemName] - quantity
if inventory.items[itemName] <= 0 then
inventory.items[itemName] = nil
end
return true
end
local function getInventory(player)
return inventoryData[player.UserId]
end
Players.PlayerAdded:Connect(createInventory)
Players.PlayerRemoving:Connect(function(player)
inventoryData[player.UserId] = nil
end)
-- Export functions
return {
addItem = addItem,
removeItem = removeItem,
getInventory = getInventory
}`,
},
{
id: 'countdown-timer',
name: 'Countdown Timer UI',
description: 'Visual countdown timer with events',
category: 'ui',
code: `local Players = game:GetService("Players")
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
-- Create ScreenGui
local screenGui = Instance.new("ScreenGui")
screenGui.Name = "TimerGui"
screenGui.Parent = playerGui
-- Create timer label
local timerLabel = Instance.new("TextLabel")
timerLabel.Size = UDim2.new(0, 200, 0, 50)
timerLabel.Position = UDim2.new(0.5, -100, 0, 20)
timerLabel.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
timerLabel.BackgroundTransparency = 0.5
timerLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
timerLabel.Font = Enum.Font.GothamBold
timerLabel.TextSize = 24
timerLabel.Text = "60"
timerLabel.Parent = screenGui
local function startCountdown(duration, onComplete)
for i = duration, 0, -1 do
timerLabel.Text = tostring(i)
-- Change color as timer runs out
if i <= 10 then
timerLabel.TextColor3 = Color3.fromRGB(255, 0, 0)
elseif i <= 30 then
timerLabel.TextColor3 = Color3.fromRGB(255, 255, 0)
else
timerLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
end
task.wait(1)
end
timerLabel.Text = "TIME'S UP!"
if onComplete then
onComplete()
end
task.wait(2)
timerLabel.Text = "0"
end
-- Example usage
startCountdown(60, function()
print("Timer completed!")
end)`,
},
{
id: 'sound-manager',
name: 'Sound/Music Manager',
description: 'Manage background music and sound effects',
category: 'tools',
code: `local SoundService = game:GetService("SoundService")
local SoundManager = {}
SoundManager.sounds = {}
SoundManager.music = nil
-- Add sound to manager
function SoundManager:addSound(name, soundId, volume)
local sound = Instance.new("Sound")
sound.Name = name
sound.SoundId = "rbxassetid://" .. soundId
sound.Volume = volume or 0.5
sound.Parent = SoundService
self.sounds[name] = sound
return sound
end
-- Play sound effect
function SoundManager:playSound(name)
local sound = self.sounds[name]
if sound then
sound:Play()
else
warn("Sound not found: " .. name)
end
end
-- Set background music
function SoundManager:setMusic(soundId, volume)
if self.music then
self.music:Stop()
self.music:Destroy()
end
self.music = Instance.new("Sound")
self.music.Name = "BackgroundMusic"
self.music.SoundId = "rbxassetid://" .. soundId
self.music.Volume = volume or 0.3
self.music.Looped = true
self.music.Parent = SoundService
self.music:Play()
end
-- Stop music
function SoundManager:stopMusic()
if self.music then
self.music:Stop()
end
end
-- Fade in/out
function SoundManager:fade(sound, targetVolume, duration)
local startVolume = sound.Volume
local steps = duration * 30 -- 30 FPS
local increment = (targetVolume - startVolume) / steps
for i = 1, steps do
sound.Volume = sound.Volume + increment
task.wait(1/30)
end
sound.Volume = targetVolume
end
-- Example usage:
-- SoundManager:addSound("Jump", 123456, 0.5)
-- SoundManager:playSound("Jump")
-- SoundManager:setMusic(789012, 0.3)
return SoundManager`,
},
{
id: 'pathfinding-npc',
name: 'Pathfinding NPC',
description: 'NPC that follows player using PathfindingService',
category: 'advanced',
code: `local PathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local npc = script.Parent
local humanoid = npc:WaitForChild("Humanoid")
local rootPart = npc:WaitForChild("HumanoidRootPart")
local target = workspace:WaitForChild("TargetPart") -- Change to your target
local updateRate = 0.5
local maxDistance = 50
local path = PathfindingService:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
WaypointSpacing = 4,
})
local function getNextWaypoint(targetPosition)
local success, errorMsg = pcall(function()
path:ComputeAsync(rootPart.Position, targetPosition)
end)
if success and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
if #waypoints > 1 then
return waypoints[2] -- Return next waypoint
end
else
warn("Path computation failed: " .. tostring(errorMsg))
end
return nil
end
local function followPath()
while true do
if target and (rootPart.Position - target.Position).Magnitude <= maxDistance then
local waypoint = getNextWaypoint(target.Position)
if waypoint then
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
end
else
humanoid:MoveTo(rootPart.Position) -- Stop moving
end
task.wait(updateRate)
end
end
-- Start following
spawn(followPath)`,
},
{
id: 'checkpoint-system',
name: 'Checkpoint System',
description: 'Save player checkpoints and respawn at last checkpoint',
category: 'gameplay',
code: `local Players = game:GetService("Players")
local checkpoints = workspace:WaitForChild("Checkpoints"):GetChildren()
local playerCheckpoints = {}
-- Sort checkpoints by name (Checkpoint1, Checkpoint2, etc.)
table.sort(checkpoints, function(a, b)
return tonumber(a.Name:match("%d+")) < tonumber(b.Name:match("%d+"))
end)
local function setupCheckpoints()
for i, checkpoint in pairs(checkpoints) do
checkpoint.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChild("Humanoid")
if humanoid then
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then
local currentCheckpoint = playerCheckpoints[player.UserId] or 0
if i > currentCheckpoint then
playerCheckpoints[player.UserId] = i
checkpoint.BrickColor = BrickColor.new("Bright green")
-- Visual feedback
local originalSize = checkpoint.Size
checkpoint.Size = originalSize * 1.2
task.wait(0.2)
checkpoint.Size = originalSize
print(player.Name .. " reached checkpoint " .. i)
end
end
end
end)
end
end
Players.PlayerAdded:Connect(function(player)
playerCheckpoints[player.UserId] = 0
player.CharacterAdded:Connect(function(character)
task.wait(0.1) -- Wait for character to load
local checkpointIndex = playerCheckpoints[player.UserId]
if checkpointIndex > 0 then
local checkpoint = checkpoints[checkpointIndex]
if checkpoint then
character:MoveTo(checkpoint.Position + Vector3.new(0, 3, 0))
end
end
end)
end)
setupCheckpoints()`,
},
{
id: 'team-system',
name: 'Team System',
description: 'Auto-assign players to balanced teams',
category: 'gameplay',
code: `local Teams = game:GetService("Teams")
local Players = game:GetService("Players")
-- Create teams if they don't exist
local function createTeam(name, color)
local team = Teams:FindFirstChild(name)
if not team then
team = Instance.new("Team")
team.Name = name
team.TeamColor = color
team.AutoAssignable = false
team.Parent = Teams
end
return team
end
local redTeam = createTeam("Red", BrickColor.new("Bright red"))
local blueTeam = createTeam("Blue", BrickColor.new("Bright blue"))
local function getTeamPlayerCount(team)
local count = 0
for _, player in pairs(Players:GetPlayers()) do
if player.Team == team then
count = count + 1
end
end
return count
end
local function assignToSmallestTeam(player)
local redCount = getTeamPlayerCount(redTeam)
local blueCount = getTeamPlayerCount(blueTeam)
if redCount <= blueCount then
player.Team = redTeam
else
player.Team = blueTeam
end
print(player.Name .. " assigned to " .. player.Team.Name .. " team")
end
Players.PlayerAdded:Connect(function(player)
assignToSmallestTeam(player)
player.CharacterAdded:Connect(function(character)
task.wait(0.1)
-- Give team color to character
local bodyColors = character:FindFirstChild("Body Colors")
if bodyColors then
bodyColors.HeadColor = player.Team.TeamColor
bodyColors.TorsoColor = player.Team.TeamColor
bodyColors.LeftArmColor = player.Team.TeamColor
bodyColors.RightArmColor = player.Team.TeamColor
bodyColors.LeftLegColor = player.Team.TeamColor
bodyColors.RightLegColor = player.Team.TeamColor
end
end)
end)`,
},
{
id: 'chat-commands',
name: 'Custom Chat Commands',
description: 'Player chat commands for emotes and actions',
category: 'tools',
code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local commands = {
["/dance"] = function(player)
local character = player.Character
if character then
local humanoid = character:FindFirstChild("Humanoid")
if humanoid then
-- Play dance emote
local danceAnimation = Instance.new("Animation")
danceAnimation.AnimationId = "rbxassetid://507770239"
local track = humanoid:LoadAnimation(danceAnimation)
track:Play()
return true, "Dancing!"
end
end
return false, "Cannot dance"
end,
["/sit"] = function(player)
local character = player.Character
if character then
local humanoid = character:FindFirstChild("Humanoid")
if humanoid then
humanoid.Sit = true
return true, "Sitting down"
end
end
return false, "Cannot sit"
end,
["/jump"] = function(player)
local character = player.Character
if character then
local humanoid = character:FindFirstChild("Humanoid")
if humanoid then
humanoid.Jump = true
return true, "Jumping!"
end
end
return false, "Cannot jump"
end,
["/reset"] = function(player)
if player.Character then
player.Character:BreakJoints()
return true, "Resetting character"
end
return false, "Cannot reset"
end,
}
Players.PlayerAdded:Connect(function(player)
player.Chatted:Connect(function(message)
local lowerMessage = string.lower(message)
for command, func in pairs(commands) do
if string.sub(lowerMessage, 1, #command) == command then
local success, result = func(player)
if success then
print(player.Name .. ": " .. result)
else
warn(player.Name .. ": " .. result)
end
break
end
end
end)
end)`,
},
{
id: 'morph-system',
name: 'Character Morphing',
description: 'Change player appearance/morph into different models',
category: 'gameplay',
code: `local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- Store morphs in ReplicatedStorage
local morphsFolder = ReplicatedStorage:WaitForChild("Morphs")
local function applyMorph(player, morphName)
local character = player.Character
if not character then
return false, "Character not found"
end
local morph = morphsFolder:FindFirstChild(morphName)
if not morph then
return false, "Morph not found"
end
local humanoid = character:FindFirstChild("Humanoid")
if not humanoid then
return false, "Humanoid not found"
end
-- Store original values
local originalWalkSpeed = humanoid.WalkSpeed
local originalJumpPower = humanoid.JumpPower
-- Clear existing accessories
for _, accessory in pairs(character:GetChildren()) do
if accessory:IsA("Accessory") or accessory:IsA("Hat") then
accessory:Destroy()
end
end
-- Apply morph appearance
local morphClone = morph:Clone()
for _, part in pairs(morphClone:GetChildren()) do
if part:IsA("Accessory") or part:IsA("Hat") then
part.Parent = character
elseif part:IsA("BodyColors") then
local bodyColors = character:FindFirstChild("Body Colors")
if bodyColors then
bodyColors.HeadColor = part.HeadColor
bodyColors.TorsoColor = part.TorsoColor
bodyColors.LeftArmColor = part.LeftArmColor
bodyColors.RightArmColor = part.RightArmColor
bodyColors.LeftLegColor = part.LeftLegColor
bodyColors.RightLegColor = part.RightLegColor
end
end
end
-- Optionally modify stats
if morphClone:FindFirstChild("WalkSpeed") then
humanoid.WalkSpeed = morphClone.WalkSpeed.Value
end
if morphClone:FindFirstChild("JumpPower") then
humanoid.JumpPower = morphClone.JumpPower.Value
end
morphClone:Destroy()
return true, "Morphed into " .. morphName
end
-- Example: Touch pad to morph
local morphPad = workspace:WaitForChild("MorphPad")
morphPad.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChild("Humanoid")
if humanoid then
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then
local success, message = applyMorph(player, "Ninja")
print(message)
end
end
end)`,
},
{
id: 'kill-brick',
name: 'Kill Brick',
description: 'Instantly kill player on touch (lava, void, etc.)',
category: 'beginner',
code: `local killBrick = script.Parent
-- Make it look dangerous
killBrick.BrickColor = BrickColor.new("Really red")
killBrick.Material = Enum.Material.Neon
-- Optional: Add particle effects
local particleEmitter = Instance.new("ParticleEmitter")
particleEmitter.Texture = "rbxasset://textures/particles/smoke_main.dds"
particleEmitter.Color = ColorSequence.new(Color3.fromRGB(255, 0, 0))
particleEmitter.Size = NumberSequence.new(2)
particleEmitter.Lifetime = NumberRange.new(1, 2)
particleEmitter.Rate = 50
particleEmitter.Parent = killBrick
-- Debounce to prevent multiple deaths
local debounce = {}
killBrick.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChild("Humanoid")
if humanoid then
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
-- Debounce check
if player and not debounce[player.UserId] then
debounce[player.UserId] = true
-- Kill the player
humanoid.Health = 0
print(player.Name .. " touched the kill brick!")
-- Reset debounce after respawn
task.wait(2)
debounce[player.UserId] = nil
elseif not player then
-- Kill NPCs or other humanoids
humanoid.Health = 0
end
end
end)`, end)`,
}, },
]; ];