Code Samples | Documentation - Roblox Creator Hub (2024)

The following samples show you how to carry out common scripting tasks inRoblox. Where applicable, corresponding 3D objects or models are provided. Youcan import the samples directly into your inventory where you can view themin the Studio Toolbox or open them directly in Studio.

Action ManagerProvides a wrapper for ContextActionService that displays actions on-screen. Input prompts automatically change based on the latest input type, rather than being set once based on peripherals.
Admin CommandsDemonstrates an admin command system using TextChatCommands. Command functions are stored in the Commands module and have an included permission level. Permission levels are determined from group rankings or a manual override set in the Admins module.
Beam BetweenGiven two attachments and a beam prefab, this class continuously orients duplicates of the attachments to face each other so that the beam remains straight.Also provides an API to enable/disable the beam and its orientation updates.
Change Part Color On TouchDemonstrates changing the color of a part upon being touched by a player's character. The color change is debounced to ensure the Touched event does not trigger a color change too quickly. The part's color is randomly set using math.random.
Character Loaded WrapperProvides an API to use when referencing a Player's character to make sure it is "Fully loaded", which is defined as: 1) Character is a descendant of workspace 2) Character has a PrimaryPart set 3) Character contains a child which is a Humanoid 4) The Humanoid's RootPart property is not nil
Character Path BeamCreates a guiding beam from the bottom of the local character to a destination attachment. Useful for guiding players towards objectives in order to progress.
Cloud ConfigDemonstrates a cloud configuration system where flag values can be set in DataStore and are automatically polled for updates by live servers.
Code Reservation ServiceDemonstrates a system to reserve and hand out single-use codes.
Create Instance TreeCreates instances with given properties based on the given tree data table. This streamlines the tedious process of calling Instance.new and setting each property by creating a table of properties and a ClassName instead.
Crossfading Two SoundsCrossfading is an audio editing technique that creates a smooth transition between two audio clips. Demonstrates crossfading between two sounds indefinitely.
Data Store RetriesDataStoreWrapper provides a retry mechanism for Data Stores that respects the order in which requests were made.
Donation LeaderboardAn example of a simple donation leaderboard. DevProducts IDs can be placed in the DonationProducts ModuleScript and will be displayed on the leaderboard to purchase. Upon purchase, the player's donation amount is incremented based on how many robux were spent.
Find First Child With AttributeSearches children of an instance, returning the first child containing an attribute matching the given name and value.The DemoScript removes flavors from an ice cream cone in the correct order using findFirstChildWithAttribute
RaycastingThe fireRaycast function fires a ray from an Attachment position, visualizing the path of the ray and the surface normal that was hit. A model named "Device" rotates around in a circle, pointing the ray at various objects.
Model Following a PlayerThe FollowingAttachment module creates an attachment that trails on the ground at some max distance behind a player's character.DemoScript uses constraints to align a rock part's position and orientation with the attachment such that the rock follows each player's character.The attachment stops updating and the rock is destroyed when the character dies.
Format TimeFormats a number of seconds into a pretty string of Hours, Minutes, and Seconds. If all hours are 0, they are omitted. If all hours and all minutes are 0, they are both omitted. Leading 0's from hours are removed. If hours are omitted, leading 0's from minutes are removed. If hours and minutes are omitted, leading 0's from seconds are removed.The DemoScript uses formatTime to display a timer that rapidly increases on a Part.
GeofencingDemonstrates a geofencing system to block content from users based on their region.
Get Character AttachmentReturns the attachment corresponding with AttachmentName under the character.The DemoScript uses getCharacterAttachment to correctly attach a pizza slice to a character's RightGripAttachment.
Input CategorizerThe InputCategorizer module categorizes various UserInputTypes (MouseButton1, MouseButton2, Gamepad1/2/3, etc.) into more manageable categories and provides an event for when the last input category changes, rather than last UserInputType.
Isometric CameraDemonstrates how to update a player's camera to create an Isometric Camera style. The camera updates every render step to ensure the camera maintains a constant distance from the player, as well as follows the player as they move.
Leader ElectionDemonstrates how to run a loop on a single server at once using MemoryStores. Useful for things like global matchmaking code that only need to run on one server at a time.
Lighting PresetsDemonstrates a system for storing lighting presets and updating the lighting settings from those presets. Presets can be set directly or tweened between to create e.g. a day/night cycle.
Playing an AnimationThe loadAnimationTrack function is used to load an animation on an Animator by providing an animation asset ID.
Loading ScreenDemonstrates an example of a loading screen. The `updateDetailText` function provides the ability to update text on the loading screen with information on what is happening behind the scenes. A spinner gives the user confidence that the game is still running.Note: the sample must be placed within ReplicatedFirst to work properly.
Moderation SystemDemonstrates a simple moderation system that can kick users from any server or ban them for arbitrary lengths of time.
Play Smoke PuffPlays a particle animation of a puff of smoke at the location, volume, and size of a given part.
Player Lifecycle EventsDemonstrates connecting to common player, character and humanoid events. Events covered: PlayerAdded, PlayerRemoving, CharacterAdded, CharacterRemoving, CharacterAppearanceLoaded and Died (humanoid).
Portal DoorDemonstrates a portal door system that allows a player to walk into a small exterior building and appear inside a larger interior.
Retry Async`retryAsync` retries function calls that may fail, and provides various arguments to describe the retry behavior. The first argument is the function it calls repeatedly until it either succeeds or is called the maximum number of times specified by `maxAttempts`. The optional third and fourth arguments allow you to customize the initial pause time and the exponent used to increase the pause time with each retry. The optional fifth argument allows you to specify a function call handler, used to make each function call (default is pcall). `retryAsync` returns a boolean indicating whether the final call to the given function was successful, and the return values of the final call (if successful) or the error message (if not successful).DemoScript provides an example using retryAsync to call a function that intentionally has a chance to error. Results of each call and the final result are printed.
Safe Player AddedCalls the given callback for all existing players in the game, and any that join thereafter.Useful in situations where you want to run code for every player, even players who are already in the game.The DemoScript uses safePlayerAdded to ensure all players in the game have a billboard with their name above their character's heads.
Custom EventSignal is a custom event that works as a replacement for BindableEvents to create custom events and replicates the behavior of RBXScriptSignal. Objects are passed by reference, which is not possible with BindableEvents.
Sprint with ButtonDemonstrates how to increase a player's speed when specific inputs are pressed. This sample implements left shift to run on keyboard, X to run on gamepad, and a touch button for mobile. The input buttons can be modified to any input desired.
ThreadQueueThreadQueue can be used to queue functions so that they don't all run at once. In this example, 10 functions are added to a queue at the same time, and then executed in order with a 1s delay between them.
Toggling Gui FramesDemonstrates how to show and hide different frames within a Gui. The example starts with a menu button visible to the player. When pressed, the menu button is hidden and a menu window appears. Clicking the 'X' at the top right corner of the menu will bring the user back to the original view.
Tween GroupLinks a group of tweens together, allowing them to be played, paused and cancelled as one.Note: TweenGroup does not support PlaybackState or Completed events.
Using TweenService on a ModelDemonstrates how to properly tween a model. Models should be tweened from an anchored part. If parts within the model are unanchored, weld these parts to the anchored part. Otherwise the unanchored parts will not follow the model as it tweens. In this case, the Base part is set as the HealthPack's PrimaryPart and all other parts in the model are welded to it.
Parallax PortalDemonstrates a portal with a 'depth' effect achieved with parallaxing images.
Leaderboard ModuleThe Leaderboard Module updates a player's leaderboard with a name (statName) and value. The module creates the initial leaderboard as well as the stat for the player if it does not already exist.The demo used the Leaderboard Module to update all player's leaderboards with a "Points" stat that increases over time.
Purchase HandlingThis sample demonstrates an approach to safely and robustly awarding developer product purchases to players
Player DataThis sample demonstrates an approach to storing and accessing player data
Code Samples | Documentation - Roblox Creator Hub (2024)

FAQs

Does Roblox use C++? ›

In the case of Roblox, C++ is likely used for various aspects of the platform, including: Engine Development: The core engine that powers Roblox games, including rendering, physics, networking, and audio systems, is written in C++.

What code does Roblox Creator use? ›

Roblox uses the coding language Lua.

What is the AI that writes Roblox code? ›

Code Assist is primarily designed to assist proficient Roblox scripters in writing code more efficiently. Due to the limitations of the model and the size of our training data set, it still requires scripters to review and modify the code suggestions. For novice scripters, you are encouraged to use Code Assist.

How do you write Roblox codes? ›

In Roblox, code is typed inside of scripts using the coding language Lua. Games often have separate scripts for each thing the game needs to do. The library template already has a script named StoryManager which you'll add more code to for your word game.

Is Lua easier than Python? ›

Kids who have studied both languages with FunTech tend to say that Lua is easier to learn than Python. However, as with any type of coding, it's down to opinion and experience.

What is the very first Roblox game to reach 1B+ visits? ›

MeepCity was the first game on Roblox to pass 1 billion total visits.

Is Roblox easy to code? ›

Roblox Studio uses Lua as its scripting language because it is easy to learn, fast, and flexible. Lua is a scripting language that is widely used in the gaming industry, and it is well-suited to being embedded in other applications.

Is Lua hard to learn? ›

Is Lua easy to learn? While every language has its complexities, Lua is one of the easier-to-learn languages and is excellent for beginners interested in image processing or game development. Many of the courses listed above are designed for beginners and have students creating their first game in no time.

What was Roblox originally called? ›

The beta version of Roblox was created by co-founders David Baszucki and Erik Cassel in 2004 under the name DynaBlocks. Baszucki started testing the first demos that year. In 2005, the company changed its name to Roblox.

Can AI really write code? ›

Introduction. In recent years, artificial intelligence (AI) has made significant advances in its ability to complete various tasks that were once thought to be exclusive to humans. This includes the ability to write code.

Is Roblox adding AI? ›

Through our free Roblox Studio app, we've released a suite of generative AI tools that are uniquely designed for Roblox workflows and trained on Roblox-specific content.

Who coded Roblox? ›

Roblox Corporation (/ˈroʊblɒks/ ROH-bloks) is an American video game developer based in San Mateo, California. Founded in 2004 by David Baszucki and Erik Cassel, the company is the developer of Roblox, which was released in 2006. As of December 31, 2023, the company employs over 2,400 people.

How do I claim 1000 Robux codes? ›

Head to the Gift Card Redemption Page; Enter the purchased Roblox Code of 1000 Robux; Press the Redeem button to finish the process; Robux have been successfully added to your account!"

Does Roblox use Python? ›

Does Roblox use Python? Roblox is not written in Python, and Roblox scripting is not compatible with the Python coding language, instead using Lua as the Studio programming language.

What script does Roblox use? ›

Roblox scripts use the Luau programming language, which is derived from Lua 5.1. Compared to Lua 5.1, Luau adds performance enhancements and many useful features, including an optional typing system, string interpolation, and generalized iteration for tables.

Do games still use C++? ›

Games are also developed by using other programming languages like Python and Java but for speed and better control mainly C++ and C# are used. Virtually all game engines are written in C++.

Is Lua similar to C++? ›

Performance and Execution: C++ is a compiled language that generates machine-level code, resulting in faster execution and better performance. Lua, on the other hand, is an interpreted language, which means it is executed at runtime using an interpreter.

Is Roblox using C#? ›

C# and Luau

For scripting, Unity uses C#. Roblox uses Luau, a scripting language derived from Lua 5.1.

What programming language is used on Roblox? ›

Roblox scripts use the Luau programming language, which is derived from Lua 5.1.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Reed Wilderman

Last Updated:

Views: 6082

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.