### IKControl Setup Example Source: https://create.roblox.com/docs/reference/engine/classes/IKControl This sample demonstrates the basic setup for an IKControl that manipulates a character's left arm to reach a specific point in the world. ```APIDOC ## IKControl Setup This sample shows the basic setup for an [IKControl](/docs/reference/engine/classes/IKControl.md) that moves a character's left arm to reach for a point in the world. ```lua local character = script.Parent.Character local humanoid = character.Humanoid local root = character.HumanoidRootPart -- Create a new attachment to use as the IKControl.Target local target = Instance.new("Attachment") target.CFrame = CFrame.new(-1, 0, -1) target.Parent = root local ikControl = Instance.new("IKControl") ikControl.Type = Enum.IKControlType.Position ikControl.EndEffector = character.LeftHand ikControl.ChainRoot = character.LeftUpperArm ikControl.Target = target ikControl.Parent = humanoid ``` ``` -------------------------------- ### Get and Set Plugin Setting Source: https://create.roblox.com/docs/reference/engine/classes/Plugin This example retrieves a setting value using a key. If the setting does not exist, it prints nil. Otherwise, it prints a welcome message and sets the setting to true. ```lua local RAN_BEFORE_KEY = "RanBefore" local didRunBefore = plugin:GetSetting(RAN_BEFORE_KEY) if didRunBefore then print("Welcome back!") else plugin:SetSetting(RAN_BEFORE_KEY, true) print("Welcome! Thanks for installing this plugin!") end ``` -------------------------------- ### Video Player Setup (Server Side) Source: https://create.roblox.com/docs/reference/engine/classes/VideoPlayer Sets up a VideoPlayer, VideoDisplay, and AudioEmitter on the server, connecting them with Wires. This example demonstrates creating the necessary instances and parenting them to the workspace. Note that server-side playback is not ideal for client synchronization. ```lua -- This should be in a "Script" with RunContext set to "Legacy" or "Server" -- Create what the video is displayed on local videoScreenPart = Instance.new("Part") videoScreenPart.Anchored = true videoScreenPart.Size = Vector3.new(12, 6, 1) videoScreenPart.CFrame = CFrame.new(0, 5, 0) videoScreenPart.Parent = workspace local videoScreenUI = Instance.new("SurfaceGui") videoScreenUI.Parent = videoScreenPart local videoDisplay = Instance.new("VideoDisplay") videoDisplay.Size = UDim2.new(1, 0, 1, 0) videoDisplay.Parent = videoScreenUI -- Create where a video asset originates from local videoSource = Instance.new("VideoPlayer") videoSource.VideoContent = Content.fromUri("rbxassetid://5608359401") videoSource.Looping = true videoSource.Parent = videoScreenPart -- Create where the video's audio emits from local speakerPart = Instance.new("Part") speakerPart.Anchored = true speakerPart.Parent = workspace local audioEmitter = Instance.new("AudioEmitter") audioEmitter.Parent = speakerPart -- Create and connect wires so that the video visually renders and emits audio local videoWire = Instance.new("Wire") videoWire.SourceInstance = videoSource videoWire.TargetInstance = videoDisplay videoWire.Parent = videoSource local audioWire = Instance.new("Wire") audioWire.SourceInstance = videoSource audioWire.TargetInstance = audioEmitter audioWire.Parent = videoSource -- Play the video -- Note: Playing a video on the server does not guarantee it is loaded or synced for all clients, playing on the client is preferred videoSource:Play() ``` -------------------------------- ### Initialize, Get, and Set Server Attributes in Studio Source: https://create.roblox.com/docs/reference/engine/classes/MatchmakingService This example demonstrates how to initialize, retrieve, and update server attributes using MatchmakingService. It includes checks for Studio environment to ensure proper initialization and provides error handling for attribute operations. ```lua local MatchmakingService = game:GetService("MatchmakingService") local RunService = game:GetService("RunService") if RunService:IsStudio() then -- Sets up initial attributes and schema for testing MatchmakingService:InitializeServerAttributesForStudio({ Level = "Advanced", Elo = 123.456, TrainingMode = true }) end -- Retrieves the Level attribute local currentLevel, errorMessage = MatchmakingService:GetServerAttribute("Level") if errorMessage then warn(errorMessage) else print("Current level: " .. currentLevel) end -- Updates the Level attribute value to Advanced local success, errorMessage = MatchmakingService:SetServerAttribute("Level", "Advanced") if not success then warn("Failed to update server attribute [Level] to [Advanced] due to error: " .. errorMessage) else print("Successfully set [Level] to [Advanced]") end ``` -------------------------------- ### Get Test Args Example Source: https://create.roblox.com/docs/reference/engine/classes/StudioTestService Retrieves arguments passed to ExecutePlayModeAsync or ExecuteRunModeAsync for the current test session. This example demonstrates printing the received arguments. Note that this may fail if called from a client LocalScript; server-side calls are recommended. ```lua local StudioTestService = game:GetService("StudioTestService") local args = StudioTestService:GetTestArgs() print("Received args:", args) ``` -------------------------------- ### Sidechain Compression Example Source: https://create.roblox.com/docs/reference/engine/classes/AudioCompressor Demonstrates how to use AudioCompressor with a sidechain input to duck ambience around an explosion sound. This setup requires creating an AudioDeviceOutput, AudioPlayers for the main audio and sidechain trigger, an AudioCompressor, and Wire instances to connect them. ```lua local deviceOutput: AudioDeviceOutput = Instance.new("AudioDeviceOutput") deviceOutput.Parent = workspace local explosionPlayer: AudioPlayer = Instance.new("AudioPlayer") explosionPlayer.Parent = workspace explosionPlayer.AssetId = "rbxassetid://1835333184" local ambiencePlayer = Instance.new("AudioPlayer") ambiencePlayer.AssetId = "rbxassetid://9112854440" local compressor = Instance.new("AudioCompressor") local wireToCompressor = Instance.new("Wire") local wireToSidechain = Instance.new("Wire") local wireToOutput = Instance.new("Wire") ambiencePlayer.Parent = workspace compressor.Parent = workspace wireToCompressor.Parent = workspace wireToSidechain.Parent = workspace wireToOutput.Parent = workspace wireToCompressor.SourceInstance = ambiencePlayer wireToCompressor.TargetInstance = compressor wireToSidechain.SourceInstance = explosionPlayer wireToSidechain.TargetInstance = compressor wireToSidechain.TargetName = "Sidechain" wireToOutput.SourceInstance = compressor wireToOutput.TargetInstance = deviceOutput ambiencePlayer:Play() ``` -------------------------------- ### Get LocalPlayer Teleport Data Source: https://create.roblox.com/docs/reference/engine/classes/TeleportService This example, when placed in StarterPlayerScripts, retrieves and prints any teleport data provided by the player's previous server upon joining the game. It uses the TeleportService. ```Lua local TeleportService = game:GetService("TeleportService") local teleportData = TeleportService:GetLocalPlayerTeleportData() print("Local player arrived with this data:", teleportData) ``` -------------------------------- ### Get Recommended Assets Example Source: https://create.roblox.com/docs/reference/engine/classes/AvatarEditorService Retrieves a list of recommended assets for a specific asset type and context asset ID. This is useful for displaying similar items in the avatar editor, similar to the website catalog. ```lua local AvatarEditorService = game:GetService("AvatarEditorService") local assets = AvatarEditorService:GetRecommendedAssetsAsync(Enum.AvatarAssetType.Hat, 9255093) for _, asset in ipairs(assets) do print(asset.Item.Name) end ``` -------------------------------- ### Example Return Character Appearance Dictionary Source: https://create.roblox.com/docs/reference/engine/classes/Players This example demonstrates the structure of the dictionary returned by Players:GetCharacterAppearanceInfoAsync for a player using a package and wearing several accessories. ```lua local result = { playerAvatarType = "R15", defaultPantsApplied = false, defaultShirtApplied = false, scales = { bodyType = 0, head = 1, height = 1.05, proportion = 0, depth = 0.92, width = 0.85, }, bodyColors = { leftArmColorId = 1030, torsoColorId = 1001, rightArmColorId = 1030, headColorId = 1030, leftLegColorId = 1001, rightLegColorId = 1001, }, assets = { { id = 1031492, assetType = { name = "Hat", id = 8, }, name = "Striped Hat", }, { id = 13062491, assetType = { name = "Face Accessory", id = 42, }, name = "Vision Française ", }, { id = 16598440, assetType = { name = "Neck Accessory", id = 43, }, name = "Red Bow Tie", }, { id = 28999228, assetType = { name = "Face", id = 18, }, name = "Joyous Surprise", }, { id = 86896488, assetType = { name = "Shirt", id = 11, }, name = "Expensive Red Tuxedo Jacket", }, { id = 86896502, assetType = { name = "Pants", id = 12, }, name = "Expensive Red Tuxedo Pants", }, { id = 376530220, assetType = { name = "Left Arm", id = 29, }, name = "ROBLOX Boy Left Arm", }, { id = 376531012, assetType = { name = "Right Arm", id = 28, }, name = "ROBLOX Boy Right Arm", }, { id = 376531300, assetType = { name = "Left Leg", id = 30, }, name = "ROBLOX Boy Left Leg", }, { id = 376531703, assetType = { name = "Right Leg", id = 31, }, name = "ROBLOX Boy Right Leg", }, { id = 376532000, assetType = { name = "Torso", id = 27, }, name = "ROBLOX Boy Torso", }, } } print(result) ``` -------------------------------- ### Tool Equipped Event Example Source: https://create.roblox.com/docs/reference/engine/classes/Tool Fires when a player equips the Tool. This example prints a message when the tool is equipped. ```lua local Tool = script.Parent local function onEquipped(_mouse) print("The tool was equipped") end Tool.Equipped:Connect(onEquipped) ``` -------------------------------- ### Preload Asset Example Source: https://create.roblox.com/docs/reference/engine/classes/ContentProvider This example preloads an asset using its ContentId. It's useful for ensuring content is available immediately when needed, such as when a player loads into a game. ```lua local ContentProvider = game:GetService("ContentProvider") ContentProvider:Preload("http://www.roblox.com/asset/?id=12222058") ``` -------------------------------- ### Get Teleport Setting Example Source: https://create.roblox.com/docs/reference/engine/classes/TeleportService Retrieves the 'isCrouching' teleport setting. This example demonstrates how to save and retrieve client-side information across teleports. ```lua local TeleportService = game:GetService("TeleportService") local isCrouching = TeleportService:GetTeleportSetting("isCrouching") ``` -------------------------------- ### Camera Listener Example Source: https://create.roblox.com/docs/reference/engine/classes/AudioListener This code sample demonstrates how to set up an AudioListener attached to the camera, along with an AudioDeviceOutput and a Wire to connect them. ```APIDOC ## Camera Listener ```lua local listener = Instance.new("AudioListener") local output = Instance.new("AudioDeviceOutput") local wire = Instance.new("Wire") listener.Parent = workspace.Camera wire.Parent = listener output.Parent = wire wire.SourceInstance = listener wire.TargetInstance = output ``` ``` -------------------------------- ### Detect Last Input Type Example Source: https://create.roblox.com/docs/reference/engine/classes/UserInputService This example gets the last UserInputType and outputs if it was keyboard input. It's useful for detecting the most recent input method. ```lua local UserInputService = game:GetService("UserInputService") if UserInputService:GetLastInputType() == Enum.UserInputType.Keyboard then print("Most recent input was keyboard!") end ``` -------------------------------- ### Record Audio with AudioRecorder Source: https://create.roblox.com/docs/reference/engine/classes/AudioRecorder This example demonstrates how to set up an AudioRecorder, wire it to an AudioPlayer, record audio, and then play the recorded content back. Note that there's no precise way to determine when audio buffer enters to trigger recording, leading to potential pre-head silence. ```lua local Workspace = game:GetService("Workspace") local audioRecorder = Instance.new("AudioRecorder") audioRecorder.Parent = Workspace local audioPlayer = Instance.new("AudioPlayer") audioPlayer.Asset = "rbxassetid://5829815715" audioPlayer.Volume = 0.8 audioPlayer.Parent = Workspace -- Wire AudioPlayer into the AudioRecorder local wire1 = Instance.new("Wire") wire1.SourceInstance = audioPlayer wire1.TargetInstance = audioRecorder wire1.Parent = audioRecorder -- There is no exact way to determine when audio buffer enters in to trigger the recording properly -- Recording will have pre-head empty silence compared to the original asset audioPlayer:Play() audioRecorder:RecordAsync() -- Start recording the AudioPlayer print("Recording...") task.wait(5) audioRecorder:Stop() -- Stop recording print("Stopped recording!") audioPlayer:Stop() audioPlayer.TimePosition = 0 -- Create output to listen the results local audioOutput = Instance.new("AudioDeviceOutput") audioOutput.Parent = Workspace local wire2 = Instance.new("Wire") wire2.SourceInstance = audioPlayer wire2.TargetInstance = audioOutput wire2.Parent = audioOutput -- Get the recorded content and play it in the AudioPlayer local resultUri = audioRecorder:GetTemporaryContent().Uri audioPlayer.Asset = resultUri if not audioPlayer.IsReady then audioPlayer:GetPropertyChangedSignal("IsReady"):Wait() end audioPlayer:Play() ``` -------------------------------- ### Get Selection Start and End Source: https://create.roblox.com/docs/reference/engine/classes/ScriptDocument Retrieves the start and end positions of the current text selection in the script editor. The positions are returned as line and character numbers. ```lua --!nocheck -- Run the following code in the Command Bar while a script is open local ScriptEditorService = game:GetService("ScriptEditorService") local function getFirstOpenDocument() local documents = ScriptEditorService:GetScriptDocuments() for _, document in documents do if not document:IsCommandBar() then return document end end return nil end local scriptDocument = getFirstOpenDocument() if scriptDocument then local startLine, startCharacter = scriptDocument:GetSelectionStart() local endLine, endCharacter = scriptDocument:GetSelectionEnd() print(`Selection start: Line {startLine}, Char {startCharacter}`) print(`Selection end: Line {endLine}, Char {endCharacter}`) else print("No scripts open") end ``` -------------------------------- ### StarterGui Methods Source: https://create.roblox.com/docs/reference/engine/classes/StarterGui This section details the methods available on the StarterGui class, allowing developers to manage CoreGui elements and create system notifications. ```APIDOC ## StarterGui:SetCoreGuiEnabled() ### Description Enables or disables specific elements of the CoreGui. ### Method StarterGui:SetCoreGuiEnabled() ### Parameters #### Path Parameters - **which** (CoreGuiType) - Required - The type of CoreGui element to enable or disable. - **enabled** (boolean) - Required - Whether to enable (`true`) or disable (`false`) the specified CoreGui element. ### Response #### Success Response (200) No specific response body is documented for this method, as it performs an action rather than returning data. ## StarterGui:SetCore() ### Description Performs a range of functions related to the CoreGui, including creating notifications and system messages. ### Method StarterGui:SetCore() ### Parameters #### Path Parameters - **property** (string) - Required - The name of the CoreGui property or function to invoke. - **value** (any) - Optional - The value to set for the property or the argument for the function. ### Response #### Success Response (200) No specific response body is documented for this method, as its behavior depends on the 'property' argument. ``` -------------------------------- ### Generate GUID with HttpService Source: https://create.roblox.com/docs/reference/engine/classes/HttpService This example uses HttpService's GenerateGUID method to generate and print a universally unique identifier. The optional boolean argument determines if the GUID should be wrapped in curly braces. ```lua local HttpService = game:GetService("HttpService") local result = HttpService:GenerateGUID(true) print(result) --> Example output: {4c50eba2-d2ed-4d79-bec1-02a967f49c58} ``` -------------------------------- ### Plugin:GetSetting and Plugin:SetSetting Example Source: https://create.roblox.com/docs/reference/engine/classes/Plugin Demonstrates how to use Plugin:GetSetting and Plugin:SetSetting to check if a plugin has run before and to set a flag indicating its first run. ```lua local RAN_BEFORE_KEY = "RunBefore" local hasRunBefore = plugin:GetSetting(RAN_BEFORE_KEY) if hasRunBefore then print("Welcome back!") else print("Thanks for installing this plugin!") plugin:SetSetting(RAN_BEFORE_KEY, true) end ``` -------------------------------- ### Get Image For KeyCode Example Source: https://create.roblox.com/docs/reference/engine/classes/UserInputService This API returns the requested image for the given KeyCode. It maps a KeyCode to a gamepad-specific icon. ```lua local UserInputService = game:GetService("UserInputService") local imageLabel = script.Parent local key = Enum.KeyCode.ButtonA local mappedIconImage = UserInputService:GetImageForKeyCode(key) imageLabel.Image = mappedIconImage ``` -------------------------------- ### Creating and Using a PluginMenu Source: https://create.roblox.com/docs/reference/engine/classes/PluginMenu This example demonstrates how to create a PluginMenu, add actions and submenus to it, and display it asynchronously. It also shows how to handle user selections from the menu. ```APIDOC ## Creating a PluginMenu and PluginMenuAction This code sample visualizes how [PluginMenus](/docs/reference/engine/classes/PluginMenu.md) and [PluginActions](/docs/reference/engine/classes/PluginAction.md) behave when created for a [Plugin](/docs/reference/engine/classes/Plugin.md). Outside of this example, you should not parent the plugin or its functional components to the experience's workspace. After executing the code, changing the created [BoolValue](/docs/reference/engine/classes/BoolValue.md) in the experience's workspace opens the plugin's menus. Selecting an action from the menus the function connected to the trigger signal. ```lua -- This code can be pasted into the Command Bar, but only once local pluginMenu = plugin:CreatePluginMenu(math.random(), "Test Menu") pluginMenu.Name = "Test Menu" pluginMenu:AddNewAction("ActionA", "A", "rbxasset://textures/loading/robloxTiltRed.png") pluginMenu:AddNewAction("ActionB", "B", "rbxasset://textures/loading/robloxTilt.png") local subMenu = plugin:CreatePluginMenu(math.random(), "C", "rbxasset://textures/explosion.png") subMenu.Name = "Sub Menu" subMenu:AddNewAction("ActionD", "D", "rbxasset://textures/whiteCircle.png") subMenu:AddNewAction("ActionE", "E", "rbxasset://textures/icon_ROBUX.png") pluginMenu:AddMenu(subMenu) pluginMenu:AddSeparator() pluginMenu:AddNewAction("ActionF", "F", "rbxasset://textures/sparkle.png") local toggle = Instance.new("BoolValue") toggle.Name = "TogglePluginMenu" toggle.Parent = workspace local function onToggled() if toggle.Value then toggle.Value = false local selectedAction = pluginMenu:ShowAsync() if selectedAction then print("Selected Action:", selectedAction.Text, "with ActionId:", selectedAction.ActionId) else print("User did not select an action!") end end end toggle.Changed:Connect(onToggled) ``` ``` -------------------------------- ### ScriptDocument:GetSelectionStart Source: https://create.roblox.com/docs/reference/engine/classes/ScriptDocument Gets the start position of the current text selection in the script editor. This is the smaller of the cursor and anchor positions. ```APIDOC ## ScriptDocument:GetSelectionStart ### Description Gets the smaller of the cursor position and anchor. If the editor has no selection, they are the same value. *Security: PluginSecurity · Thread Safety: Unsafe* ### Returns `Tuple` ### Example ```lua --!nocheck -- Run the following code in the Command Bar while a script is open local ScriptEditorService = game:GetService("ScriptEditorService") local function getFirstOpenDocument() local documents = ScriptEditorService:GetScriptDocuments() for _, document in documents do if not document:IsCommandBar() then return document end end return nil end local scriptDocument = getFirstOpenDocument() if scriptDocument then local startLine, startCharacter = scriptDocument:GetSelectionStart() local endLine, endCharacter = scriptDocument:GetSelectionEnd() print(`Selection start: Line {startLine}, Char {startCharacter}`) print(`Selection end: Line {endLine}, Char {endCharacter}`) else print("No scripts open") end ``` ``` -------------------------------- ### Get Camera Render CFrame (VR Example) Source: https://create.roblox.com/docs/reference/engine/classes/Camera Retrieve the camera's actual CFrame as it is rendered, which is crucial for VR where head transformations affect the view. This example shows how to calculate the render CFrame, incorporating VR head movements. ```lua local UserInputService = game:GetService("UserInputService") local Workspace = game:GetService("Workspace") local camera = Workspace.CurrentCamera local headCFrame = UserInputService:GetUserCFrame(Enum.UserCFrame.Head) headCFrame = headCFrame.Rotation + headCFrame.Position * camera.HeadScale renderCFrame = camera.CFrame * headCFrame ``` -------------------------------- ### Demonstrate Sound Class Methods Source: https://create.roblox.com/docs/reference/engine/classes/Sound This sample demonstrates the core functionalities of the Sound class, including Play, Stop, Pause, and Resume. It also shows how to connect to playback events like Played, Paused, Resumed, and Stopped. Ensure a Sound object is created and loaded before use. ```lua -- create a sound local sound = Instance.new("Sound", game.Workspace) sound.SoundId = "rbxassetid://9120386436" if not sound.IsLoaded then ssound.Loaded:Wait() end -- listen for events sound.Played:Connect(function(_soundId) print("Sound.Played event") end) sound.Paused:Connect(function(_soundId) print("Sound.Paused event") end) sound.Resumed:Connect(function(_soundId) print("Sound.Resumed event") end) sound.Stopped:Connect(function(_soundId) print("Sound.Stopped event") end) sound:Play() print("play", sound.Playing, sound.TimePosition) -- play true 0 task.wait(10) sound:Pause() print("pause", sound.Playing, sound.TimePosition) -- pause false 10 task.wait(3) sound:Resume() print("play", sound.Playing, sound.TimePosition) -- play true 10 task.wait(3) sound:Stop() print("stop", sound.Playing, sound.TimePosition) -- stop false 0 task.wait(3) sound:Play() print("play", sound.Playing, sound.TimePosition) -- play true 0 ``` -------------------------------- ### Create a DockWidgetPluginGui Source: https://create.roblox.com/docs/reference/engine/classes/DockWidgetPluginGui This example demonstrates how to create a dockable widget GUI using the Plugin:CreateDockWidgetPluginGuiAsync method. This is the primary way to instantiate a DockWidgetPluginGui. ```Lua local StudioService = game:GetService("Studio") local success, dockWidget = pcall(StudioService.CreateDockWidgetPluginGuiAsync, StudioService, "MyWidgetName") if success then -- Configure the dockWidget here print("Dock widget created successfully!") else warn("Failed to create dock widget:", dockWidget) end ``` -------------------------------- ### Print Names of Workspace Children Source: https://create.roblox.com/docs/reference/engine/classes/Instance This example demonstrates how to get all direct children of the workspace and print their names using a numeric loop. ```lua local children = workspace:GetChildren() for i = 1, #children do print(i, children[i].Name) end ``` -------------------------------- ### Configure Sound Emitter Size and Playback Source: https://create.roblox.com/docs/reference/engine/classes/Sound This example demonstrates how to create a Part with an attached Sound, configure its EmitterSize for attenuation, and toggle playback using a ClickDetector. The sound plays locally and its volume drops off with distance. ```lua local part = Instance.new("Part") part.Anchored = true part.Position = Vector3.new(0, 3, 0) part.BrickColor = BrickColor.new("Bright red") part.Name = "MusicBox" part.Parent = workspace -- create a sound local sound = Instance.new("Sound", part) sound.SoundId = "rbxassetid://9120386436" sound.EmitterSize = 5 -- decrease the emitter size (for earlier volume drop off) sound.Looped = true sound.Parent = part local clickDetector = Instance.new("ClickDetector") clickDetector.Parent = part -- toggle the sound playing / not playing clickDetector.MouseClick:Connect(function() if not sound.IsPlaying then part.BrickColor = BrickColor.new("Bright green") sound:Play() else part.BrickColor = BrickColor.new("Bright red") sound:Stop() end end) ``` -------------------------------- ### Measuring Text Size Source: https://create.roblox.com/docs/reference/engine/classes/GetTextBoundsParams This example demonstrates how to create a GetTextBoundsParams instance, set its properties, and use it with TextService:GetTextBoundsAsync() to get the text bounds. ```APIDOC ## Measuring Text Size This example demonstrates how to create a GetTextBoundsParams instance, set its properties, and use it with TextService:GetTextBoundsAsync() to get the text bounds. ```lua local TextService = game:GetService("TextService") -- Declare parameters local params = Instance.new("GetTextBoundsParams") params.Text = "Hello world!" params.Font = Font.new("rbxasset://fonts/families/GrenzeGotisch.json", Enum.FontWeight.Thin) params.Size = 20 params.Width = 200 local success, bounds = pcall(function() return TextService:GetTextBoundsAsync(params) end) if success then print(bounds) end ``` ``` -------------------------------- ### Pyramid Builder with BasePart.Size Source: https://create.roblox.com/docs/reference/engine/classes/BasePart Constructs a pyramid by stacking parts that get progressively smaller. Colors the parts to blend between a start and end color. ```lua local TOWER_BASE_SIZE = 30 local position = Vector3.new(50, 50, 50) local hue = math.random() local color0 = Color3.fromHSV(hue, 1, 1) local color1 = Color3.fromHSV((hue + 0.35) % 1, 1, 1) local model = Instance.new("Model") model.Name = "Tower" for i = TOWER_BASE_SIZE, 1, -2 do local part = Instance.new("Part") part.Size = Vector3.new(i, 2, i) part.Position = position part.Anchored = true part.Parent = model -- Tween from color0 and color1 local perc = i / TOWER_BASE_SIZE part.Color = Color3.new( color0.R * perc + color1.R * (1 - perc), color0.G * perc + color1.G * (1 - perc), color0.B * perc + color1.B * (1 - perc) ) position = position + Vector3.new(0, part.Size.Y, 0) end model.Parent = workspace ``` -------------------------------- ### Get Current Studio Theme Example Source: https://create.roblox.com/docs/reference/engine/classes/Studio This Lua code snippet demonstrates how to access the Studio.Theme property to print the current Studio theme. It uses the settings() function. ```lua print("The current Studio theme is:", settings().Studio.Theme) ``` -------------------------------- ### Basic IKControl Setup Source: https://create.roblox.com/docs/reference/engine/classes/IKControl This sample demonstrates the fundamental setup for an IKControl to make a character's left arm reach a specific point in the world. Ensure the character, Humanoid, and HumanoidRootPart are correctly referenced. ```lua local character = script.Parent.Character local humanoid = character.Humanoid local root = character.HumanoidRootPart -- Create a new attachment to use as the IKControl.Target local target = Instance.new("Attachment") target.CFrame = CFrame.new(-1, 0, -1) target.Parent = root local ikControl = Instance.new("IKControl") ikControl.Type = Enum.IKControlType.Position ikControl.EndEffector = character.LeftHand ikControl.ChainRoot = character.LeftUpperArm ikControl.Target = target ikControl.Parent = humanoid ``` -------------------------------- ### Get Unparented Instances Result Structure Source: https://create.roblox.com/docs/reference/engine/classes/SceneAnalysisService This example shows the expected structure of the dictionary returned by SceneAnalysisService:GetUnparentedInstancesAsync. It details how instances are organized by host script and then by class. ```lua { Name = "UnparentedInstances", Size = 47, Children = { { Name = "ServerScriptService.Gameplay.Combat", Size = 30, Children = { { Name = "Part", Size = 22 }, { Name = "Attachment", Size = 8 }, }}, { Name = "(unknown)", Size = 17, Children = { { Name = "Frame", Size = 12 }, { Name = "Sound", Size = 5 }, }}, } } ``` -------------------------------- ### Creating a PluginAction Source: https://create.roblox.com/docs/reference/engine/classes/Plugin This code sample demonstrates how to create a PluginAction using the Plugin:CreatePluginAction() method. The action, when triggered, prints 'Hello world!' to the output. Ensure this code is pasted into the Command Bar only once to avoid errors. ```lua local pluginAction = plugin:CreatePluginAction( "HelloWorldAction", "Hello World", "Prints a 'Hello world!'", "rbxasset://textures/sparkle.png", true ) pluginAction.Name = "Test Action" local function actionTriggered() print("Hello world!") end pluginAction.Triggered:Connect(actionTriggered) ``` -------------------------------- ### Server-side Avatar Setup and Client Preview Source: https://create.roblox.com/docs/reference/engine/classes/AvatarCreationService This server-side script demonstrates how to automatically set up a custom avatar using a body model and a layered shirt model. It then loads the generated avatar on the server and signals a client event to load it for local preview. Includes progress reporting for the setup process. ```lua local AvatarCreationService = game:GetService("AvatarCreationService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local LoadAvatarEvent = ReplicatedStorage.LoadAvatarEvent local generatedAvatars = {} -- Must be called on the server local function setupAvatar(player: Player, avatarModel: Model, layeredShirtModel : Model) local arguments = { Body = avatarModel, Accessories = {} } local accessoryArgument = { AccessoryType = Enum.AccessoryType.Shirt, IsLayered = true, Instance = layeredShirtModel, } table.insert(arguments.Accessories, accessoryArgument) local pcallSuccess, result = pcall(function() local generationId = AvatarCreationService:AutoSetupAvatarAsync( player, arguments, function(progressInfo) print(`AutoSetup progress: {progressInfo.Progress * 100}%`) end ) -- Load and store on the server to use with PromptCreateAvatarAsync local humanoidDescription = AvatarCreationService:LoadGeneratedAvatarAsync(generationId) generatedAvatars[generationId] = humanoidDescription -- Signal the client so it can load the avatar for local preview LoadAvatarEvent:FireClient(player, generationId) end) if not pcallSuccess then warn("Avatar setup failed:", result) end end ``` -------------------------------- ### Get Price Levels for Users Source: https://create.roblox.com/docs/reference/engine/classes/MarketplaceService Retrieves regionalized price levels for a list of user IDs. This example maps user IDs to their respective price levels for easy lookup. ```lua -- Get the MarketplaceService local MarketplaceService = game:GetService("MarketplaceService") -- Define a function to retrieve price levels for a list of users local function getPriceLevels(userIds) local success, result = pcall(function() return MarketplaceService:GetUsersPriceLevelsAsync(userIds) end) if success then -- Map each PriceLevelInfo to a UserId -> PriceLevel lookup table local lookup = {} for _, info in ipairs(result) do lookup[info.UserId] = info.PriceLevel end return lookup else warn("Error getting price levels:", result) return nil end end -- Example using placeholder IDs local user1Id = 123456789 local user2Id = 987654321 -- Call the function and store the result local priceLevels = getPriceLevels({user1Id, user2Id}) -- If successful, print each user's level if priceLevels then print("Price level for User 1:", priceLevels[user1Id]) print("Price level for User 2:", priceLevels[user2Id]) else print("Failed to retrieve price levels.") end ``` -------------------------------- ### StarterGui.ShowDevelopmentGui Source: https://create.roblox.com/docs/reference/engine/classes/StarterGui Determines whether the contents of StarterGui are visible in the Studio environment. ```APIDOC ## Property: StarterGui.ShowDevelopmentGui ### Description This property controls the visibility of StarterGui's contents within the Roblox Studio editor. When true, the UI elements are displayed in Studio. ### Type boolean ### Access ReadWrite ### Security Read: None Write: None ### Serialization Can Load: true Can Save: true ### Thread Safety ReadSafe ### Category Data ### Capabilities UI ``` -------------------------------- ### Get Direct Children of an Instance (Generic Loop) Source: https://create.roblox.com/docs/reference/engine/classes/Instance Use GetChildren to retrieve an array of all direct children of an instance. This example demonstrates iterating through the children using a generic for loop. ```lua local Workspace = game:GetService("Workspace") -- Generic loop example local children = Workspace:GetChildren() for i, child in children do print(child.Name .. " is child number " .. i) end ``` -------------------------------- ### Creating an R15 Character Rig from Package Assets Source: https://create.roblox.com/docs/reference/engine/classes/Humanoid This example demonstrates how to create a full R15 character rig by loading assets from a package ID, assembling the parts, and then using Humanoid:BuildRigFromAttachments to establish the rig's structure. Ensure the package ID points to a valid R15 character model. ```lua local AssetService = game:GetService("AssetService") local InsertService = game:GetService("InsertService") local MarketplaceService = game:GetService("MarketplaceService") local PACKAGE_ASSET_ID = 193700907 -- Circuit Breaker local function addAttachment(part, name, position, orientation) local attachment = Instance.new("Attachment") attachment.Name = name attachment.Parent = part if position then attachment.Position = position end if orientation then attachment.Orientation = orientation end return attachment end local function createBaseCharacter() local character = Instance.new("Model") local humanoid = Instance.new("Humanoid") humanoid.Parent = character local rootPart = Instance.new("Part") rootPart.Name = "HumanoidRootPart" rootPart.Size = Vector3.new(2, 2, 1) rootPart.Transparency = 1 rootPart.Parent = character addAttachment(rootPart, "RootRigAttachment") local head = Instance.new("Part") head.Name = "Head" head.Size = Vector3.new(2, 1, 1) head.Parent = character local headMesh = Instance.new("SpecialMesh") headMesh.Scale = Vector3.new(1.25, 1.25, 1.25) headMesh.MeshType = Enum.MeshType.Head headMesh.Parent = head local face = Instance.new("Decal") face.Name = "face" face.Texture = "rbxasset://textures/face.png" face.Parent = head addAttachment(head, "FaceCenterAttachment") addAttachment(head, "FaceFrontAttachment", Vector3.new(0, 0, -0.6)) addAttachment(head, "HairAttachment", Vector3.new(0, 0.6, 0)) addAttachment(head, "HatAttachment", Vector3.new(0, 0.6, 0)) addAttachment(head, "NeckRigAttachment", Vector3.new(0, -0.5, 0)) return character, humanoid end local function createR15Package(packageAssetId) local packageAssetInfo = MarketplaceService:GetProductInfoAsync(packageAssetId) local character, humanoid = createBaseCharacter() character.Name = packageAssetInfo.Name local assetIds = AssetService:GetAssetIdsForPackageAsync(packageAssetId) for _, assetId in pairs(assetIds) do local limb = InsertService:LoadAsset(assetId) local r15 = limb:FindFirstChild("R15") if r15 then for _, part in pairs(r15:GetChildren()) do part.Parent = character end else for _, child in pairs(limb:GetChildren()) do child.Parent = character end end end humanoid:BuildRigFromAttachments() return character end local r15Package = createR15Package(PACKAGE_ASSET_ID) r15Package.Parent = workspace ``` -------------------------------- ### Get Direct Children of an Instance (Numeric Loop) Source: https://create.roblox.com/docs/reference/engine/classes/Instance Use GetChildren to retrieve an array of all direct children of an instance. This example demonstrates iterating through the children using a numeric for loop. ```lua local Workspace = game:GetService("Workspace") -- Numeric loop example local children = Workspace:GetChildren() for i = 1, #children do local child = children[i] print(child.Name .. " is child number " .. i) end ``` -------------------------------- ### Demonstrate Sound Playback Control Source: https://create.roblox.com/docs/reference/engine/classes/Sound This sample demonstrates the behavior of Sound.Play, Sound.Stop, Sound.Pause, and Sound.Resume methods on Sound.Playing and Sound.TimePosition. It also shows how to connect to sound events like Played, Paused, Resumed, and Stopped. ```lua local sound = Instance.new("Sound", game.Workspace) sound.SoundId = "rbxassetid://9120386436" if not sound.IsLoaded then ssound.Loaded:Wait() end -- listen for events sound.Played:Connect(function(_soundId) print("Sound.Played event") end) sound.Paused:Connect(function(_soundId) print("Sound.Paused event") end) sound.Resumed:Connect(function(_soundId) print("Sound.Resumed event") end) sound.Stopped:Connect(function(_soundId) print("Sound.Stopped event") end) sound:Play() print("play", sound.Playing, sound.TimePosition) -- play true 0 task.wait(10) sound:Pause() print("pause", sound.Playing, sound.TimePosition) -- pause false 10 task.wait(3) sound:Resume() print("play", sound.Playing, sound.TimePosition) -- play true 10 task.wait(3) sound:Stop() print("stop", sound.Playing, sound.TimePosition) -- stop false 0 task.wait(3) sound:Play() print("play", sound.Playing, sound.TimePosition) -- play true 0 ``` -------------------------------- ### Get Currently Visible Lines Source: https://create.roblox.com/docs/reference/engine/classes/ScriptDocument Fetches the start and end line numbers of the text currently visible in the editor's viewport. This accounts for scrolling and potential code folding. ```lua --!nocheck -- Run the following code in the Command Bar while a script is open local ScriptEditorService = game:GetService("ScriptEditorService") local function getFirstOpenDocument() local documents = ScriptEditorService:GetScriptDocuments() for _, document in documents do if not document:IsCommandBar() then return document end end return nil end local scriptDocument = getFirstOpenDocument() if scriptDocument then local firstLine, lastLine = scriptDocument:GetViewport() print(`Currently viewing lines {firstLine} to {lastLine}`) else print("No scripts open") end ``` -------------------------------- ### Click Event Example Source: https://create.roblox.com/docs/reference/engine/classes/PluginToolbarButton This code sample demonstrates creating a PluginToolbar and a PluginToolbarButton on it, then connecting a function onClick to the PluginToolbarButton.Click event. When pressed, the button will print "Hello, world" to the output. ```APIDOC ## Event: PluginToolbarButton.Click ### Description This event fires when the [PluginToolbarButton](/docs/reference/engine/classes/PluginToolbarButton.md) is pressed and released by the user. See also [SetActive()](/docs/reference/engine/classes/PluginToolbarButton.md) to manually set the state of the button. *Security: PluginSecurity* ### Example ```lua assert(plugin, "This script must be run as a plugin") local toolbar = plugin:CreateToolbar("Hello World Plugin Toolbar") local pluginToolbarButton = ttoolbar:CreateButton("Print Hello World", "Click this button to print Hello World!", "rbxassetid://133293265") local function onClick() print("Hello, world") end pluginToolbarButton.Click:Connect(onClick) ``` ``` -------------------------------- ### StarterCharacterScripts Source: https://create.roblox.com/docs/reference/engine/classes/StarterCharacterScripts Stores instances to be parented to a player's character when it spawns. ```APIDOC ## Class: StarterCharacterScripts > Stores instances to be parented to a player's character when it spawns. ## Description The [StarterCharacterScripts](/docs/reference/engine/classes/StarterCharacterScripts.md) container stores scripts to be parented to a player's [Player.Character](/docs/reference/engine/classes/Player.md) when it spawns. Unlike scripts stored in the [StarterPlayerScripts](/docs/reference/engine/classes/StarterPlayerScripts.md) folder, these scripts will not persist when the character respawns. If a [LocalScript](/docs/reference/engine/classes/LocalScript.md) named `Animate`, `Sound`, or `Health` is placed in this container, it will replace the default script that manages character animations, character sounds, and character health regeneration respectively. ``` -------------------------------- ### Create and Use a WebStreamClient for SSE Source: https://create.roblox.com/docs/reference/engine/classes/HttpService This example demonstrates how to create a raw stream client to connect to a local LLM server using Server-Sent Events (SSE). It includes handling incoming messages and errors, and properly disconnecting the client. ```lua local HttpService = game:GetService("HttpService") local LOCAL_LLM_PORT = "http://localhost:11434/api/generate?stream=true" local function handleMessage(message) -- Parse events depending on the stream type -- If response Content-Type header is JSON, you can decode it like this: local json = HttpService:JSONDecode(message) end local function handleError(responseStatusCode, errorMessage) print("Stream error with response code:", responseStatusCode) end local function request() local sse_client = HttpService:CreateWebStreamClient(Enum.WebStreamClientType.RawStream, { -- Llama3.2 LLM server running locally using Ollama Url = LOCAL_LLM_PORT, Method = "POST", Headers = { ["Content-Type"] = "application/json", -- When sending JSON, set this! }, Body = HttpService:JSONEncode({ model="llama3.2", prompt ="Tell me a funny joke"}), }) local messageConnection = sse_client.MessageReceived:Connect(handleMessage) local errorConnection = sse_client.Error:Connect(handleError) sse_client.Closed:Wait() messageConnection:Disconnect() errorConnection:Disconnect() sse_client:close() end -- Remember to wrap the function in a 'pcall' to prevent the script from breaking if the request fails local success, message = pcall(request) if not success then print("WebStreamClient failed:", message) end ``` -------------------------------- ### Find a Part's Mass Source: https://create.roblox.com/docs/reference/engine/classes/BasePart This example demonstrates how to get the mass of a newly created Part. It creates a part, anchors it, and then retrieves its mass using the GetMass method, printing the result. ```lua local myPart = Instance.new("Part") myPart.Size = Vector3.new(4, 6, 4) myPart.Anchored = true myPart.Parent = workspace local myMass = myPart:GetMass() print("My part's mass is " .. myMass) ``` -------------------------------- ### Get GlobalDataStore Instance Source: https://create.roblox.com/docs/reference/engine/classes/DataStoreService This example retrieves a default data store instance. The GlobalDataStore behaves like a regular Instance, allowing functions like GetChildren() to execute without error. ```lua local DataStoreService = game:GetService("DataStoreService") local GlobalDataStore = DataStoreService:GetGlobalDataStore() print(GlobalDataStore.Name) ``` -------------------------------- ### Load and Freeze Animation Example Source: https://create.roblox.com/docs/reference/engine/classes/AnimationTrack Demonstrates loading an animation and then freezing it at a specific time and percentage using the previously defined functions. ```lua local animation = Instance.new("Animation") animation.AnimationId = "rbxassetid://507765644" local humanoid = script.Parent:WaitForChild("Humanoid") local animator = humanoid:WaitForChild("Animator") local animationTrack = animator:LoadAnimation(animation) freezeAnimationAtTime(animationTrack, 0.5) freezeAnimationAtPercent(animationTrack, 50) ``` -------------------------------- ### Creating and Playing a VideoFrame Source: https://create.roblox.com/docs/reference/engine/classes/VideoFrame Demonstrates how to instantiate a VideoFrame, set its video content, and play it after it has loaded. Ensure to replace the placeholder asset ID with a valid one. ```lua local screenPart = Instance.new("Part") screenPart.Parent = workspace local surfaceGui = Instance.new("SurfaceGui") surfaceGui.Parent = screenPart local videoFrame = Instance.new("VideoFrame") videoFrame.Parent = surfaceGui videoFrame.Looped = true videoFrame.Video = "rbxassetid://" -- add an asset ID to this while not videoFrame.IsLoaded do task.wait() end videoFrame:Play() ```