| Players: Not CreatableServiceThe Players service contains Player objects for presently |
| connected clients to a Roblox server. It also contains information about a |
| place's configuration. It can fetch information about players not connected to |
| the server, such as character appearances, friends, and avatar thumbnail.Code SamplesThis code sample listens for players spawning and gives them Sparkles in their |
| head. It does this by defining two functions, onPlayerSpawned and |
| onPlayerAdded.Give Sparkles to Everyonelocal Players = game:GetService("Players") |
|
|
| local function onCharacterAdded(character) |
| -- Give them sparkles on their head if they don't have them yet |
| if not character:FindFirstChild("Sparkles") then |
| local sparkles = Instance.new("Sparkles") |
| sparkles.Parent = character:WaitForChild("Head") |
| end |
| end |
|
|
| local function onPlayerAdded(player) |
| -- Check if they already spawned in |
| if player.Character then |
| onCharacterAdded(player.Character) |
| end |
| -- Listen for the player (re)spawning |
| player.CharacterAdded:Connect(onCharacterAdded) |
| end |
|
|
| Players.PlayerAdded:Connect(onPlayerAdded)SummaryPropertiesBubbleChat: booleanIndicates whether or not bubble chat is enabled. It is set with the |
| Players:SetChatStyle() method.READ ONLYNOT REPLICATEDCharacterAutoLoads: booleanIndicates whether Class.Character|Characters will respawn automatically.NOT REPLICATEDClassicChat: booleanIndicates whether or not classic chat is enabled; set by the |
| Players:SetChatStyle() method.READ ONLYNOT REPLICATEDLocalPlayer: PlayerThe Player that the LocalScript is running for.READ ONLYNOT REPLICATEDMaxPlayers: numberThe maximum number of players that can be in a server.READ ONLYNOT REPLICATEDPreferredPlayers: numberThe preferred number of players for a server.READ ONLYNOT REPLICATEDRespawnTime: numberControls the amount of time taken for a players character to respawn.UseStrafingAnimations: booleanNOT SCRIPTABLEProperties inherited from InstanceArchivable: booleanDetermines if an Instance can be cloned using |
| Instance:Clone() or saved to file.ClassName: stringA read-only string representing the class this Instance belongs |
| to.READ ONLYNOT REPLICATEDName: stringA non-unique identifier of the Instance.Parent: InstanceDetermines the hierarchical parent of the Instance.NOT REPLICATEDRobloxLocked: booleanA deprecated property that used to protect CoreGui objects.HIDDENarchivable: booleanHIDDENNOT REPLICATEDDEPRECATEDclassName: stringREAD ONLYNOT REPLICATEDDEPRECATEDMethodsChat(message: string): void Makes the local player chat the given message.GetPlayerByUserId(userId: number): Player Returns the Player with the given UserId if |
| they are in-game.GetPlayerFromCharacter(character: Model): Player Returns the Player whose Character |
| matches the given instance, or nil if one cannot be found.GetPlayers(): Objects Returns a table of all presently connected Player objects.SetChatStyle(style: ChatStyle): void Sets whether BubbleChat and ClassicChat are being used, and tells TeamChat |
| and Chat what to do.TeamChat(message: string): void Makes the LocalPlayer chat the given message, which will only be |
| viewable by users on the same team.CreateHumanoidModelFromDescription(description: HumanoidDescription, rigType: HumanoidRigType, assetTypeVerification: AssetTypeVerification): Model YIELDSReturns a character Model equipped with everything specified in the passed |
| in HumanoidDescription, and is R6 or R15 as specified by the rigType.CreateHumanoidModelFromUserId(userId: number): Model YIELDSReturns a character Model set-up with everything equipped to match the |
| avatar of the user specified by the passed in userId.GetCharacterAppearanceInfoAsync(userId: number): table YIELDSReturns information about the character appearance of a given user.GetFriendsAsync(userId: number): FriendPages YIELDSReturns a FriendPages object which contains information for all of |
| the given player's friends.GetHumanoidDescriptionFromOutfitId(outfitId: number): HumanoidDescription YIELDSReturns the HumanoidDescription for a specified outfit, which will be set |
| with the parts/colors/Animations etc of the outfit.GetHumanoidDescriptionFromUserId(userId: number): HumanoidDescription YIELDSReturns a HumanoidDescription which specifies everything equipped for the |
| avatar of the user specified by the passed in userId.GetNameFromUserIdAsync(userId: number): string YIELDSSends a query to the Roblox website for the username of an account with a |
| given UserId.GetUserIdFromNameAsync(userName: string): number YIELDSSends a query to the Roblox website for the userId |
| of an account with a given username.GetUserThumbnailAsync(userId: number, thumbnailType: ThumbnailType, thumbnailSize: ThumbnailSize): Tuple YIELDSReturns the content URL of a player thumbnail given the size and type, as |
| well as a boolean describing if the image is ready to use.Methods inherited from InstanceAddTag(tag: string): void Applies a tag to the instance.ClearAllChildren(): void This function destroys all of an Instance's children.Clone(): Instance Create a copy of an object and all its descendants, ignoring objects that |
| are not Archivable.Destroy(): void Sets the Instance.Parent property to nil, locks the |
| Instance.Parent property, disconnects all connections, and calls |
| Destroy on all children.FindFirstAncestor(name: string): Instance Returns the first ancestor of the Instance whose |
| Instance.Name is equal to the given name.FindFirstAncestorOfClass(className: string): Instance Returns the first ancestor of the Instance whose |
| Instance.ClassName is equal to the given className.FindFirstAncestorWhichIsA(className: string): Instance Returns the first ancestor of the Instance for whom |
| Instance:IsA() returns true for the given className.FindFirstChild(name: string, recursive: boolean): Instance Returns the first child of the Instance found with the given name.FindFirstChildOfClass(className: string): Instance Returns the first child of the Instance whose |
| ClassName is equal to the given className.FindFirstChildWhichIsA(className: string, recursive: boolean): Instance Returns the first child of the Instance for whom |
| Instance:IsA() returns true for the given className.FindFirstDescendant(name: string): Instance Returns the first descendant found with the given Instance.Name.GetActor(): Actor Returns the Actor associated with the Instance, if any.GetAttribute(attribute: string): Variant Returns the attribute which has been assigned to the given name.GetAttributeChangedSignal(attribute: string): RBXScriptSignal Returns an event that fires when the given attribute changes.GetAttributes(): table Returns a dictionary of string → variant pairs for each of the |
| Instance's attributes.GetChildren(): Objects Returns an array containing all of the Instance's children.GetDebugId(scopeLength: number): string NOT BROWSABLEReturns a coded string of the Instances DebugId used internally by |
| Roblox.GetDescendants(): Array CUSTOM LUA STATEReturns an array containing all of the descendants of the instance.GetFullName(): string Returns a string describing the Instance's ancestry.GetPropertyChangedSignal(property: string): RBXScriptSignal Get an event that fires when a given property of an object changes.GetTags(): Array Gets an array of all tags applied to the instance.HasTag(tag: string): boolean Check whether the instance has a given tag.IsA(className: string): boolean CUSTOM LUA STATEReturns true if an Instance's class matches or inherits from a |
| given class.IsAncestorOf(descendant: Instance): boolean Returns true if an Instance is an ancestor of the given |
| descendant.IsDescendantOf(ancestor: Instance): boolean Returns true if an Instance is a descendant of the given ancestor.Remove(): void DEPRECATEDSets the object's Parent to nil, and does the same for all its |
| descendants.RemoveTag(tag: string): void Removes a tag from the instance.SetAttribute(attribute: string, value: Variant): void Sets the attribute with the given name to the given value.WaitForChild(childName: string, timeOut: number): Instance CUSTOM LUA STATE, CAN YIELDReturns the child of the Instance with the given name. If the |
| child does not exist, it will yield the current thread until it does.children(): Objects DEPRECATEDReturns an array of the object's children.clone(): Instance DEPRECATEDdestroy(): void DEPRECATEDfindFirstChild(name: string, recursive: boolean): Instance DEPRECATEDgetChildren(): Objects DEPRECATEDisA(className: string): boolean DEPRECATED, CUSTOM LUA STATEisDescendantOf(ancestor: Instance): boolean DEPRECATEDremove(): void DEPRECATEDEventsPlayerAdded(player: Player): RBXScriptSignal Fires when a player enters the game.PlayerMembershipChanged(player: Player): RBXScriptSignal Fires when the game server recognizes that a player's membership has |
| changed.PlayerRemoving(player: Player): RBXScriptSignal Fires when a player is about to leave the game.UserSubscriptionStatusChanged(user: Player, subscriptionId: string): RBXScriptSignal Fires when the game server recognizes that the user's status for a certain |
| subscription has changed.Events inherited from InstanceAncestryChanged(child: Instance, parent: Instance): RBXScriptSignal Fires when the Instance.Parent property of the object or one of |
| its ancestors is changed.AttributeChanged(attribute: string): RBXScriptSignal Fires whenever an attribute is changed on the Instance.Changed(property: string): RBXScriptSignal Fired immediately after a property of an object changes.ChildAdded(child: Instance): RBXScriptSignal Fires after an object is parented to this Instance.ChildRemoved(child: Instance): RBXScriptSignal Fires after a child is removed from this Instance.DescendantAdded(descendant: Instance): RBXScriptSignal Fires after a descendant is added to the Instance.DescendantRemoving(descendant: Instance): RBXScriptSignal Fires immediately before a descendant of the Instance is removed.Destroying(): RBXScriptSignal Fires immediately before the instance is destroyed via |
| Instance:Destroy().childAdded(child: Instance): RBXScriptSignal DEPRECATEDPropertiesBubbleChatbooleanRead OnlyNot ReplicatedRead ParallelThe BubbleChat Players property indicates whether or not bubble |
| chat is enabled. It is set with the Players:SetChatStyle() method |
| using the ChatStyle enum. |
| When this chat mode is enabled, the game displays chats in the chat user |
| interface at the top-left corner of the screen. |
| There are two other chat modes, Players.ClassicChat and a chat |
| mode where both classic and bubble chat are enabled.CharacterAutoLoadsbooleanNot ReplicatedRead ParallelThe CharacterAutoLoads property indicates whether |
| Class.Character|Characters will respawn automatically. The default value |
| is true. |
| If this property is disabled (false), player Class.Character|Characters |
| will not spawn until the Player:LoadCharacter() function is called |
| for each Player, including when players join the experience. |
| This can be useful in experiences where players have finite lives, such as |
| competitive games in which players do not respawn until a game round ends.Code SamplesThis example demonstrates one possible usage of the |
| Players.CharacterAutoLoads property. |
| The example below respawns all players in the game, if dead, once every 10 |
| seconds. This means that players who die 1 second after all players respawn |
| must wait 9 seconds until the script loads all Player.Character again. |
| First, this script removes a player's character when they die and the |
| Humanoid.Died function fires. This is done so that the respawn loop |
| that executes every 10 seconds reloads that player when it does not find the |
| player's character in the Workspace. |
| To work as expected, this example should be run within a Script.Player Respawn Timerlocal Players = game:GetService("Players") |
|
|
| -- Set CharacterAutoLoads to false |
| Players.CharacterAutoLoads = false |
|
|
| -- Remove player's character from workspace on death |
| Players.PlayerAdded:Connect(function(player) |
| while true do |
| local char = player.CharacterAdded:Wait() |
| char.Humanoid.Died:Connect(function() |
| char:Destroy() |
| end) |
| end |
| end) |
|
|
| -- Respawn all dead players once every 10 seconds |
| while true do |
| local players = Players:GetChildren() |
|
|
| -- Check if each player is dead by checking if they have no character, if dead load that player's character |
| for _, player in pairs(players) do |
| if not workspace:FindFirstChild(player.Name) then |
| player:LoadCharacter() |
| end |
| end |
|
|
| -- Wait 10 seconds until next respawn check |
| task.wait(10) |
| endClassicChatbooleanRead OnlyNot ReplicatedRead ParallelIndicates whether or not classic chat is enabled. This property is set by |
| the Players:SetChatStyle() method using the ChatStyle enum. |
| When this chat mode is enabled, the game displays chats in a bubble above |
| the sender's head. |
| There are two other chat modes, Players.BubbleChat and a chat mode |
| where both classic and bubble chat are enabled.LocalPlayerPlayerRead OnlyNot ReplicatedRead ParallelLocalPlayer is a read-only property which refers to the Player |
| whose client is running the experience. |
| This property is only defined for LocalScripts and |
| ModuleScripts required by them, since they run on the |
| client. For the server, on which Script objects run their code, |
| this property is nil. |
| Loading GUIs |
| When creating loading GUIs using ReplicatedFirst, sometimes a |
| LocalScript can run before the LocalPlayer is available. In this |
| case, you should yield until it becomes available by using |
| Instance:GetPropertyChangedSignal()MaxPlayersnumberRead OnlyNot ReplicatedRead ParallelThe MaxPlayers property determines the maximum number of players that |
| can be in a server. This property can only be set through a specific |
| place's settings on the |
| Creator Dashboard or through |
| Game Settings.PreferredPlayersnumberRead OnlyNot ReplicatedRead ParallelThe PreferredPlayers property indicates the number of players to which |
| Roblox's matchmaker will fill servers. This number will be less than the |
| maximum number of players (Players.MaxPlayers) supported by the |
| experience.RespawnTimenumberRead ParallelThe RespawnTime property controls the time, in seconds, it takes for a |
| player to respawn when Players.CharacterAutoLoads is true. It |
| defaults to 5.0 seconds. |
| This is useful when you want to change how long it takes to respawn based |
| on the type of your experience but don't want to handle spawning players |
| individually. |
| Although this property can be set from within a Script, you can |
| more easily set it directly on the Players object in Studio's |
| Explorer window.UseStrafingAnimationsbooleanNot ScriptableRead ParallelProperties inherited from InstanceArchivablebooleanRead ParallelThis property determines whether an object should be |
| included when the game is published or saved, or when |
| Instance:Clone() is called on one of the object's ancestors. |
| Calling Clone directly on an object will return nil if the cloned object |
| is not archivable. Copying an object in Studio (using the 'Duplicate' or |
| 'Copy' options) will ignore the Archivable property and set Archivable to |
| true for the copy. |
| local part = Instance.new("Part") |
| print(part:Clone()) --> Part |
| part.Archivable = false |
| print(part:Clone()) --> nilClassNamestringRead OnlyNot ReplicatedRead ParallelA read-only string representing the class this Instance belongs |
| to. |
| This property can be used with various other functions of Instance that |
| are used to identify objects by type, such as Instance:IsA() or |
| Instance:FindFirstChildOfClass(). |
| Note this property is read only and cannot be altered by scripts. |
| Developers wishing to change an Instance's class will instead have |
| to create a new Instance. |
| Unlike Instance:IsA(), ClassName can be used to check if an object |
| belongs to a specific class ignoring class inheritance. For example: |
| for _, child in ipairs(game.Workspace:GetChildren()) do |
| if child.ClassName == "Part" then |
| print("Found a Part") |
| -- will find Parts in model, but NOT TrussParts, WedgeParts, etc |
| end |
| endNamestringRead ParallelA non-unique identifier of the Instance. |
| This property is an identifier that describes an object. Names are not |
| necessarily unique identifiers however; multiple children of an object may |
| share the same name. Names are used to keep the object hierarchy |
| organized, along with allowing scripts to access specific objects. |
| The name of an object is often used to access the object through the data |
| model hierarchy using the following methods: |
| local baseplate = workspace.Baseplate |
| local baseplate = workspace["Baseplate"] |
| local baseplate = workspace:FindFirstChild("BasePlate") |
| In order to make an object accessible using the dot operator, an object's |
| Name must follow a certain syntax. The objects name must start with an |
| underscore or letter. The rest of the name can only contain letters, |
| numbers, or underscores (no other special characters). If an objects name |
| does not follow this syntax it will not be accessible using the dot |
| operator and Lua will not interpret its name as an identifier. |
| If more than one object with the same name are siblings then any attempt |
| to index an object by that name will return the only one of the objects |
| found similar to Instance:FindFirstChild(), but not always the |
| desired object. If a specific object needs to be accessed through code, it |
| is recommended to give it a unique name, or guarantee that none of its |
| siblings share the same name as it. |
| Note, a full name showing the instance's hierarchy can be obtained using |
| Instance:GetFullName().ParentInstanceNot ReplicatedRead ParallelThe Parent property determines the hierarchical parent of the |
| Instance. The following terminology is commonly used when talking |
| about how this property is set: |
|
|
| An object is a child (parented to) another object when its |
| Parent is set to that object. |
| The descendants of an Instance are the children of that |
| object, plus the descendants of the children as well. |
| The ancestors of an Instance are all the objects that the |
| Instance is a descendant of. |
|
|
| It is from this property that many other API members get their name, such |
| as GetChildren and |
| FindFirstChild. |
| The Remove function sets this property to nil. |
| Calling Destroy will set the Parent of an |
| Instance and all of its descendants to nil, and also lock |
| the Parent property. An error is raised when setting the Parent of a |
| destroyed object. |
| This property is also used to manage whether an object exists in the game |
| or needs removed. As long as an objects parent is in the |
| DataModel, is stored in a variable, or is referenced by another |
| objects property, then the object remains in the game. Otherwise, the |
| object will automatically be removed. The top level DataModel |
| object (the one referred to as the game by scripts) has no parent, but |
| always has a reference held to it by the game engine, and exists for the |
| duration of a session. |
| Newly created objects using Instance.new() will not have a |
| parent, and usually will not be visible or function until one is set. The |
| most elementary creation of an object has two steps: creating the object, |
| then setting its parent. |
| -- Create a part and parent it to the workspace |
| local part = Instance.new("Part") |
| part.Parent = workspace |
| -- Instance new can also take Parent as a second parameter |
| Instance.new("NumberValue", workspace) |
| Object Replication |
| An object created by server will not replicate to clients until it is |
| parented to some object that is replicated. When creating an object then |
| setting many properties, it's recommended to set Parent last. This |
| ensures the object replicates once, instead of replicating many property |
| changes. |
| local part = Instance.new("Part") -- Avoid using the second parameter here |
| part.Anchored = true |
| part.BrickColor = BrickColor.new("Really red") |
| -- Potentially many other property changes could go here here... |
| -- Always set parent last! |
| part.Parent = workspace |
| However, if you were parenting your parts to a Model whose parent |
| hasn't been set yet, then setting the parent first would not matter as the |
| model would not have replicated yet.RobloxLockedbooleanHiddenPlugin SecurityRead ParallelThis property used to protect objects in the CoreGui service from |
| being altered by users in an unauthorized manner. It has been deprecated |
| and does not do anything.archivablebooleanHiddenNot ReplicatedDEPRECATEDRead ParallelDEPRECATEDThis deprecated property is a variant of Instance.Archivable which |
| should be used instead.classNamestringRead OnlyNot ReplicatedDEPRECATEDRead ParallelDEPRECATEDThis deprecated property is a variant of Instance.ClassName which |
| should be used instead.MethodsChatvoidPlugin SecurityThis function makes the local player chat the given message. Since this |
| item is protected, attempting to use it in a Script or |
| LocalScript will cause an error. |
| Instead, when creating a custom chat system, or a system that needs access |
| to the chat, you can use the Chat service's Chat:Chat() |
| function instead.Parametersmessage: stringThe message chatted.ReturnsvoidCode SamplesThis example demonstrates that the Players:Chat() function executes |
| without error if using the Command Bar or a Plugin (assuming the local player |
| can chat freely) and errors if executed in a Script.Players:Chat-- Command bar |
| game:GetService("Players"):Chat("Hello, world!") --Results in 'Hello, world!' appearing in the Chat log under your Player's name. |
|
|
| -- Script |
| local Players = game:GetService("Players") |
| Players:Chat("Hello, world!") --ErrorsGetPlayerByUserIdPlayerWrite ParallelThis function searches each player in Players for |
| one whose Player.UserId matches the given UserId. If such a player |
| does not exist, it simply returns nil. It is equivalent to the following |
| function: |
| local Players = game:GetService("Players") |
| local function getPlayerByUserId(userId) |
| for _, player in pairs(Players:GetPlayers()) do |
| if player.UserId == userId then |
| return player |
| end |
| end |
| end |
| This method is useful in finding the purchaser of a developer product |
| using MarketplaceService.ProcessReceipt, which provides a table |
| that includes the purchaser's UserId and not a reference to the Player |
| object itself. Most games will require a reference to the player in order |
| to grant products.ParametersuserId: numberThe Player.UserId of the player being specified.ReturnsPlayerCode SamplesPlayers:GetPlayerByUserIdlocal Players = game:GetService("Players") |
|
|
| local player = Players:GetPlayerByUserId(1) |
|
|
| if player then |
| print("Player with userId 1 is in this server! Their name is: " .. player.Name) |
| else |
| print("Player with userId 1 is not in this server!") |
| endThis code sample illustrates a |
| ProcessReceipt() callback function |
| for a game to handle purchasing of two developer products (you can add more as |
| needed). It properly checks for and records purchases using a |
| GlobalDataStore called "PurchaseHistory." |
| Most importantly, it properly returns |
| ProductPurchaseDecision.PurchaseGranted when the transaction is |
| successfully completed or if it's detected that the purchase has already |
| been granted using the "PurchaseHistory" data store.ProcessReceipt Callbacklocal MarketplaceService = game:GetService("MarketplaceService") |
| local DataStoreService = game:GetService("DataStoreService") |
| local Players = game:GetService("Players") |
|
|
| -- Data store for tracking purchases that were successfully processed |
| local purchaseHistoryStore = DataStoreService:GetDataStore("PurchaseHistory") |
|
|
| -- Table setup containing product IDs and functions for handling purchases |
| local productFunctions = {} |
| -- ProductId 123123 for a full heal |
| productFunctions[123123] = function(_receipt, player) |
| -- Logic/code for player buying a full heal (may vary) |
| if player.Character and player.Character:FindFirstChild("Humanoid") then |
| -- Heal the player to full health |
| player.Character.Humanoid.Health = player.Character.Humanoid.MaxHealth |
| -- Indicate a successful purchase |
| return true |
| end |
| end |
| -- ProductId 456456 for 100 gold |
| productFunctions[456456] = function(_receipt, player) |
| -- Logic/code for player buying 100 gold (may vary) |
| local stats = player:FindFirstChild("leaderstats") |
| local gold = stats and stats:FindFirstChild("Gold") |
| if gold then |
| gold.Value = gold.Value + 100 |
| -- Indicate a successful purchase |
| return true |
| end |
| end |
|
|
| -- The core 'ProcessReceipt' callback function |
| local function processReceipt(receiptInfo) |
| -- Determine if the product was already granted by checking the data store |
| local playerProductKey = receiptInfo.PlayerId .. "_" .. receiptInfo.PurchaseId |
| local purchased = false |
| local success, result, errorMessage |
|
|
| success, errorMessage = pcall(function() |
| purchased = purchaseHistoryStore:GetAsync(playerProductKey) |
| end) |
| -- If purchase was recorded, the product was already granted |
| if success and purchased then |
| return Enum.ProductPurchaseDecision.PurchaseGranted |
| elseif not success then |
| error("Data store error:" .. errorMessage) |
| end |
|
|
| -- Determine if the product was already granted by checking the data store |
| local playerProductKey = receiptInfo.PlayerId .. "_" .. receiptInfo.PurchaseId |
|
|
| local success, isPurchaseRecorded = pcall(function() |
| return purchaseHistoryStore:UpdateAsync(playerProductKey, function(alreadyPurchased) |
| if alreadyPurchased then |
| return true |
| end |
|
|
| -- Find the player who made the purchase in the server |
| local player = Players:GetPlayerByUserId(receiptInfo.PlayerId) |
| if not player then |
| -- The player probably left the game |
| -- If they come back, the callback will be called again |
| return nil |
| end |
|
|
| local handler = productFunctions[receiptInfo.ProductId] |
|
|
| local success, result = pcall(handler, receiptInfo, player) |
| -- If granting the product failed, do NOT record the purchase in datastores. |
| if not success or not result then |
| error("Failed to process a product purchase for ProductId: " .. tostring(receiptInfo.ProductId) .. " Player: " .. tostring(player) .. " Error: " .. tostring(result)) |
| return nil |
| end |
|
|
| -- Record the transcation in purchaseHistoryStore. |
| return true |
| end) |
| end) |
|
|
| if not success then |
| error("Failed to process receipt due to data store error.") |
| return Enum.ProductPurchaseDecision.NotProcessedYet |
| elseif isPurchaseRecorded == nil then |
| -- Didn't update the value in data store. |
| return Enum.ProductPurchaseDecision.NotProcessedYet |
| else |
| -- IMPORTANT: Tell Roblox that the game successfully handled the purchase |
| return Enum.ProductPurchaseDecision.PurchaseGranted |
| end |
| end |
|
|
| -- Set the callback; this can only be done once by one script on the server! |
| MarketplaceService.ProcessReceipt = processReceipt |
| GetPlayerFromCharacterPlayerThis function returns the Player associated with the given |
| Player.Character, or nil if one cannot be found. It is |
| equivalent to the following function: |
| local function getPlayerFromCharacter(character) |
| for _, player in pairs(game:GetService("Players"):GetPlayers()) do |
| if player.Character == character then |
| return player |
| end |
| end |
| end |
| This method is often used when some event in player's character fires |
| (such as their Humanoid dying). Such an |
| event might not directly reference the Player object, but this method |
| provides easy access. The inverse of this function can be described as |
| getting the Character of a Player. To do this, simply access the Character |
| property.Parameterscharacter: ModelA character instance that you want to get the player from.ReturnsPlayerCode SamplesPlayers:GetPlayerFromCharacterlocal Players = game:GetService("Players") |
|
|
| local character = workspace.Player |
| local player = Players:GetPlayerFromCharacter(character) |
|
|
| if player then |
| print("Player is " .. player.Name) |
| else |
| print("Player doesn't exist!") |
| endGetPlayersObjectsWrite ParallelThis method returns a table of all presently connected Player. It |
| functions the same way Instance:GetChildren() would except that it |
| only returns Player objects. It functions similarly to |
| Instance:GetChildren() when called on Players. When used |
| in conjunction with a for-loop, it is useful for iterating over all |
| players in a game. |
| Players = game:GetService("Players") |
| for i, player in pairs(Players:GetPlayers()) do |
| print(player.Name) |
| end |
| Scripts that connect to Players.PlayerAdded are often trying to |
| process every Player that connects to the game. This method is useful for |
| iterating over already-connected players that wouldn't fire |
| PlayerAdded. Using this method ensures that no |
| player is missed! |
| local Players = game:GetService("Players") |
|
|
| local function onPlayerAdded(player) |
| print("Player: " .. player.Name) |
| end |
|
|
| for _, player in pairs(Players:GetPlayers()) do |
| onPlayerAdded(player) |
| end |
| Players.PlayerAdded:Connect(onPlayerAdded)ReturnsObjectsA table containing all the players in the server.Code SamplesThis code sample listens for players spawning and gives them Sparkles in their |
| head. It does this by defining two functions, onPlayerSpawned and |
| onPlayerAdded.Give Sparkles to Everyonelocal Players = game:GetService("Players") |
|
|
| local function onCharacterAdded(character) |
| -- Give them sparkles on their head if they don't have them yet |
| if not character:FindFirstChild("Sparkles") then |
| local sparkles = Instance.new("Sparkles") |
| sparkles.Parent = character:WaitForChild("Head") |
| end |
| end |
|
|
| local function onPlayerAdded(player) |
| -- Check if they already spawned in |
| if player.Character then |
| onCharacterAdded(player.Character) |
| end |
| -- Listen for the player (re)spawning |
| player.CharacterAdded:Connect(onCharacterAdded) |
| end |
|
|
| Players.PlayerAdded:Connect(onPlayerAdded)SetChatStylevoidPlugin SecurityThis function sets whether BubbleChat and ClassicChat are being used, and |
| tells TeamChat and Chat what to do using the ChatStyle enum. Since |
| this item is protected, attempting to use it in a Script or |
| LocalScript will cause an error. |
| This function is used internally when the chat mode is set by the game.Parametersstyle: ChatStyleThe specified chat style being set.Default Value: "Classic"ReturnsvoidCode SamplesThis example demonstrates that the Players:SetChatStyle() function |
| executes without error if using the Command Bar or a Plugin and errors if |
| executed in a LocalScript. |
| When executed in the Command Bar, this code sets the chat style to Classic |
| using the ChatStyle enum.Setting a Player's Chat Style-- Command bar |
| game.Players:SetChatStyle(Enum.ChatStyle.Classic) -- Set's chat style to Classic |
|
|
| -- LocalScript |
| local Players = game:GetService("Players") |
| Players:SetChatStyle(Enum.ChatStyle.Classic) -- ErrorsTeamChatvoidPlugin SecurityThis function makes the Players.LocalPlayer chat the given |
| message, which will only be viewable by users on the same team. Since this |
| item is protected, attempting to use it in a Script or |
| LocalScript will cause an error. |
| This function is used internally when the Players.LocalPlayer |
| sends a message to their team.Parametersmessage: stringThe message being chatted.ReturnsvoidCode SamplesThis example demonstrates that the Players:TeamChat() function |
| executes without error if using the Command Bar or a Plugin and errors if |
| executed in a LocalScript. |
| When executed in the Command Bar, the function sends the specified message to |
| all players on the same Team as the Players.LocalPlayer.Sending Team Chat-- Command bar |
| game.Players:TeamChat("Hello World") -- Sends a "Hello World" message to all players on the local player's team |
|
|
| -- LocalScript |
| local Players = game:GetService("Players") |
| Players:TeamChat("Hello World") -- ErrorsCreateHumanoidModelFromDescriptionModelYieldsReturns a character Model equipped with everything specified in the passed |
| in HumanoidDescription, and is R6 or R15 as specified by the rigType.Parametersdescription: HumanoidDescriptionSpecifies the appearance of the returned character.rigType: HumanoidRigTypeSpecifies whether the returned character will be R6 or R15.assetTypeVerification: AssetTypeVerificationAsset type verification determines if this function will load models |
| or not (You should set this to Always unless you want to load |
| non-catalog assets).Default Value: "Default"ReturnsModelA Humanoid character Model.Code SamplesThis code sample creates a Humanoid Model from the passed in |
| HumanoidDescription and parents the Model to the Workspace.Create Humanoid Model From Descriptiongame.Players:CreateHumanoidModelFromDescription(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15).Parent = game.WorkspaceCreateHumanoidModelFromUserIdModelYieldsReturns a character Model set-up with everything equipped to match the |
| avatar of the user specified by the passed in userId. This includes |
| whether that character is currently R6 or R15.ParametersuserId: numberThe userId for a Roblox user. (The UserId is the number in the profile |
| of the user e.g www.roblox.com/users/1/profile).ReturnsModelA Humanoid character Model.Code SamplesThis code sample creates a Humanoid Model to match the avatar of the passed in |
| User ID, and parents the Model to the Workspace.Create Humanoid Model From A User IDgame.Players:CreateHumanoidModelFromUserId(1).Parent = game.WorkspaceGetCharacterAppearanceInfoAsynctableYieldsThis function returns information about a player's avatar (ignoring gear) |
| on the Roblox website in the form of a dictionary. It is not to be |
| confused with |
| GetCharacterAppearanceAsync, |
| which actually loads the assets described by this method. You can use |
| InsertService:LoadAsset() to load the assets that are used in the |
| player's avatar. The structure of the returned dictionary is as follows: |
| NameTypeDescriptionassetstable (see below)Describes the equipped assets (hats, body parts, etc)bodyColorstable (see below)Describes the BrickColor values for each limbbodyColors3table (see below)Describes the Color3 instance for each limb which may not match perfectly with bodyColorsdefaultPantsAppliedboolDescribes whether default pants are applieddefaultShirtAppliedboolDescribes whether default shirt is appliedemotestable (see below)Describes the equipped emote animationsplayerAvatarTypestringEither "R15" or "R6"scalestable (see below)Describes various body scaling factors |
| Assets sub-table |
| The assets table is an array of tables containing the following keys that |
| describe the assets currently equipped by the player: |
| NameTypeDescriptionidnumberThe asset ID of the equipped assetassetTypetableA table with name and id fields, each describing the kind of asset equipped ("Hat", "Face", etc.)namestringThe name of the equipped asset |
| Scales sub-table |
| The scales table has the following keys, each a number corresponding to |
| one Humanoid scaling property: bodyType, head, height, |
| proportion, depth, width.`` |
| Body Colors sub-table |
| The body colors table has the following keys, each a number corresponding |
| to a BrickColor ID number which can be used with |
| BrickColor.new(): leftArmColorId, torsoColorId, |
| rightArmColorId, headColorId, leftLegColorId, rightLegColorId.ParametersuserId: numberThe *userId of the specified player.ReturnstableA dictionary containing information about the character appearance of |
| a given user.Code SamplesSometimes it is best to see an example of the returned dictionary structure in |
| pure Lua. Here is one such example of a player whose avatar uses a package and |
| wears several hats. Can you guess who it is?Example Return Character Appearance Dictionarylocal 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)GetFriendsAsyncFriendPagesYieldsThe GetFriends Players function returns a FriendPages |
| object which contains information for all of the given |
| Player's friends. The items within the FriendPages object |
| are tables with the following fields: |
| NameTypeDescriptionIdint64The friend's UserIdUsernamestringThe friend's usernameDisplayNamestringThe display name of the friend.IsOnlineboolIf the friend is currently online |
| See the code samples for an easy way to iterate over all a player's |
| friends.ParametersuserId: numberThe userId of the player being specified.ReturnsFriendPagesCode SamplesThis code sample loads the Player.UserId of the player whose username |
| is provided at the top of the script by using |
| Players:GetUserIdFromNameAsync(). Then, it gets a FriendPages object |
| by calling Players:GetFriendsAsync() and iterates over each entry |
| using the iterPageItems function. The username of each friend is stored in a |
| table, then printed at the end.Print Roblox Friendslocal Players = game:GetService("Players") |
|
|
| local USERNAME = "Cozecant" |
|
|
| local function iterPageItems(pages) |
| return coroutine.wrap(function() |
| local pagenum = 1 |
| while true do |
| for _, item in ipairs(pages:GetCurrentPage()) do |
| coroutine.yield(item, pagenum) |
| end |
| if pages.IsFinished then |
| break |
| end |
| pages:AdvanceToNextPageAsync() |
| pagenum = pagenum + 1 |
| end |
| end) |
| end |
|
|
| -- First, get the user ID of the player |
| local userId = Players:GetUserIdFromNameAsync(USERNAME) |
| -- Then, get a FriendPages object for their friends |
| local friendPages = Players:GetFriendsAsync(userId) |
| -- Iterate over the items in the pages. For FriendPages, these |
| -- are tables of information about the friend, including Username. |
| -- Collect each username in a table |
| local usernames = {} |
| for item, _pageNo in iterPageItems(friendPages) do |
| table.insert(usernames, item.Username) |
| end |
|
|
| print("Friends of " .. USERNAME .. ": " .. table.concat(usernames, ", "))GetHumanoidDescriptionFromOutfitIdHumanoidDescriptionYieldsReturns the HumanoidDescription for a specified outfitId, which will be |
| set with the parts/colors/Animations etc of the outfit. An outfit can be |
| one created by a user, or it can be the outfit for a bundle created by |
| Roblox.ParametersoutfitId: numberThe id of the outfit for which the HumanoidDescription is sought.ReturnsHumanoidDescriptionHumanoidDescription initialized with the specification for the passed |
| in outfitId.Code SamplesThis code sample shows how to get the HumanoidDescription for bundle 799 |
| (Fishman).Get HumanoidDescription From Outfit IDlocal function getHumanoidDescriptionBundle(bundleId) |
| local function getOutfitId() |
| if bundleId <= 0 then |
| return |
| end |
| local info = game.AssetService:GetBundleDetailsAsync(bundleId) |
| if not info then |
| return |
| end |
| for _,item in pairs(info.Items) do |
| if item.Type == "UserOutfit" then |
| return item.Id |
| end |
| end |
| end |
| local itemId = getOutfitId(bundleId) |
| return (itemId and itemId > 0) and game.Players:GetHumanoidDescriptionFromOutfitId(itemId) or nil |
| end |
| game.Players:CreateHumanoidModelFromDescription(getHumanoidDescriptionBundle(799), Enum.HumanoidRigType.R15).Parent = game.WorkspaceGetHumanoidDescriptionFromUserIdHumanoidDescriptionYieldsReturns a HumanoidDescription which specifies everything equipped for the |
| avatar of the user specified by the passed in userId. Also includes scales |
| and body colors.ParametersuserId: numberThe userId for a Roblox user. (The UserId is the number in the profile |
| of the user e.g www.roblox.com/users/1/profile).ReturnsHumanoidDescriptionHumanoidDescription initialized with the passed in user's avatar |
| specification.Code SamplesThis code sample shows how to use GetHumanoidDescriptionFromUserId() to create |
| a Humanoid Model.Get HumanoidDescription From User IDgame.Players:CreateHumanoidModelFromDescription(game.Players:GetHumanoidDescriptionFromUserId(1), Enum.HumanoidRigType.R15).Parent = game.WorkspaceGetNameFromUserIdAsyncstringYieldsThe GetNameFromUserIdAsync Players function will send a query to |
| the Roblox website asking what the username is of the account with the |
| given UserId. |
| This method errors if no account exists with the given UserId. If you |
| aren't certain such an account exists, it's recommended to wrap calls to |
| this function with pcall. In addition, you can manually cache results to |
| make future calls with the same UserId fast. See the code samples to learn |
| more.ParametersuserId: numberThe Player.UserId of the player being specified.ReturnsstringThe name of a user with the specified Player.UserId.Code SamplesThis code sample demonstrates using the |
| Players:GetNameFromUserIdAsync() method to get a user's |
| Player.Name from their Player.UserId.Get Name from UserIdlocal Players = game:GetService("Players") |
|
|
| -- Example Data: |
| -- UserId: 118271 Name: "RobloxRulez" |
| -- UserId: 131963979 Name: "docsRule" |
|
|
| local nameOne = Players:GetNameFromUserIdAsync(118271) |
| local nameTwo = Players:GetNameFromUserIdAsync(131963979) |
|
|
| print(nameOne, nameTwo) |
| -- prints: "RobloxRulez docsRule" |
| This code sample demonstrates using the |
| Players:GetNameFromUserIdAsync() method to get a user's |
| Player.Name from their Player.UserId. Because |
| GetNameFromUserIdAsync() yields, you |
| can avoid calling it for the same Name using a table to |
| store each UserId:Name pair found, called a cache. |
| pcall() is used to catch the failure in case the Name |
| doesn't exist.Get Name from UserId using a cachelocal Players = game:GetService("Players") |
|
|
| -- Create a table called 'cache' to store each 'Name' as they are found. |
| -- If we lookup a 'Name' using the same 'UserId', the 'Name' will come |
| -- from cache (fast) instead of GetNameFromUserIdAsync() (yields). |
| local cache = {} |
|
|
| function getNameFromUserId(userId) |
| -- First, check if the cache contains 'userId' |
| local nameFromCache = cache[userId] |
| if nameFromCache then |
| -- if a value was stored in the cache at key 'userId', then this 'nameFromCache' |
| -- is the correct Name and we can return it. |
| return nameFromCache |
| end |
|
|
| -- If here, 'userId' was not previously looked up and does not exist in the |
| -- cache. Now we need to use GetNameFromUserIdAsync() to look up the name |
| local name |
| local success, _ = pcall(function() |
| name = Players:GetNameFromUserIdAsync(userId) |
| end) |
| if success then |
| -- if 'success' is true, GetNameFromUserIdAsync() successfully found the |
| -- name. Store this name in the cache using 'userId' as the key so we |
| -- never have to look this name up in the future. Then return name. |
| cache[userId] = name |
| return name |
| end |
| -- If here, 'success' was false, meaning GetNameFromUserIdAsync() |
| -- was unable to find the 'name' for the 'userId' provided. Warn the user |
| -- this happened and then return nothing, or nil. |
| warn("Unable to find Name for UserId:", userId) |
| return nil |
| end |
|
|
| -- Example Data: |
| -- UserId: 118271 Name: "RobloxRulez" |
| -- UserId: 131963979 Name: "docsRule" |
|
|
| -- The first time a UserId is used, GetNameFromUserIdAsync() will be called |
| local nameOne = getNameFromUserId(118271) |
| local nameTwo = getNameFromUserId(131963979) |
| -- Because 118271 was previously used, get its Name from the cache |
| local nameOneQuick = getNameFromUserId(118271) |
|
|
| print(nameOne, nameTwo, nameOneQuick) |
| -- prints: "RobloxRulez docsRule RobloxRulez" |
| GetUserIdFromNameAsyncnumberYieldsThis function will send a query to the Roblox website asking what the |
| Player.UserId is of the account with the given Player |
| name. |
| This method errors if no account exists with the given username. If you |
| aren't certain such an account exists, it's recommended to wrap calls to |
| this function with pcall. In addition, you can manually cache results to |
| quickly make future calls with the same username. See the code samples to |
| learn more.ParametersuserName: stringThe username of the player being specified.ReturnsnumberThe Player.UserId of a user whose name is specified.Code SamplesThis code sample demonstrates using the |
| Players:GetUserIdFromNameAsync() method to get a user's |
| Player.UserId from their Player.Name.Get UserId from Namelocal Players = game:GetService("Players") |
|
|
| -- Example Data: |
| -- UserId: 118271 Name: "RobloxRulez" |
| -- UserId: 131963979 Name: "docsRule" |
|
|
| local userIdOne = Players:GetUserIdFromNameAsync("RobloxRulez") |
| local userIdTwo = Players:GetUserIdFromNameAsync("docsRule") |
| print(userIdOne, userIdTwo) |
| -- prints: "118271 131963979" |
| This code sample demonstrates using the |
| Players:GetUserIdFromNameAsync() method to get a user's |
| Player.UserId from their Player.Name. Because |
| GetUserIdFromNameAsync() yields, you |
| can avoid calling it for the same UserId using a table |
| to store each Name:UserId pair found, called a cache. |
| pcall() is used to catch the failure in case the UserId |
| doesn't exist.Get UserId from Name using a cachelocal Players = game:GetService("Players") |
|
|
| -- Create a table called 'cache' to store each 'UserId' as they are found. |
| -- If we lookup a 'UserId' using the same 'Name', the 'UserId' will come |
| -- from cache (fast) instead of GetUserIdFromNameAsync() (yields). |
| local cache = {} |
|
|
| function getUserIdFromName(name) |
| -- First, check if the cache contains 'name' |
| local userIdFromCache = cache[name] |
| if userIdFromCache then |
| -- if a value was stored in the cache at key 'name', then this 'userIdFromCache' |
| -- is the correct UserId and we can return it. |
| return userIdFromCache |
| end |
|
|
| -- If here, 'name' was not previously looked up and does not exist in the |
| -- cache. Now we need to use GetUserIdFromNameAsync() to look up the userId |
| local userId |
| local success, _ = pcall(function() |
| userId = Players:GetUserIdFromNameAsync(name) |
| end) |
| if success then |
| -- if 'success' is true, GetUserIdFromNameAsync() successfully found the |
| -- userId. Store this userId in the cache using 'name' as the key so we |
| -- never have to look this userId up in the future. Then return userId. |
| cache[name] = userId |
| return userId |
| end |
| -- If here, 'success' was false, meaning GetUserIdFromNameAsync() |
| -- was unable to find the 'userId' for the 'name' provided. We can warn the |
| -- user this happened and then return nothing, or nil. |
| warn("Unable to find UserId for Name:", name) |
| return nil |
| end |
|
|
| -- Example Data: |
| -- UserId: 118271 Name: "RobloxRulez" |
| -- UserId: 131963979 Name: "docsRule" |
|
|
| -- The first time a Name is used, GetUserIdFromNameAsync() will be called |
| local userIdOne = getUserIdFromName("RobloxRulez") |
| local userIdTwo = getUserIdFromName("docsRule") |
| -- Because "RobloxRulez" was previously used, get its UserId from the cache |
| local userIdOneQuick = getUserIdFromName("RobloxRulez") |
|
|
| print(userIdOne, userIdTwo, userIdOneQuick) |
| -- prints: "118271 131963979 118271" |
| GetUserThumbnailAsyncTupleYieldsThis function returns the content URL of an image of a player's avatar |
| given their UserId, the desired image size as a |
| ThumbnailSize enum, and the desired type as a ThumbnailType |
| enum. It also returns a boolean describing if the image is ready to use. |
| Most often, this method is used with ImageLabel.Image or |
| Decal.Texture to display user avatar pictures in an experience.ParametersuserId: numberThe Player.UserId of the player being specified.thumbnailType: ThumbnailTypeA ThumbnailType describing the type of thumbnail.thumbnailSize: ThumbnailSizeA ThumbnailSize specifying the size of the thumbnail.ReturnsTupleA tuple containing the content URL of a user thumbnail based on the |
| specified parameters, and a bool describing if the image is ready to |
| be used or not.Code SamplesThis code sample displays the current player's thumbnail in a parent |
| ImageLabel by using Players:GetUserThumbnailAsync() and setting the |
| Image() property as well as its |
| Size().Display Player Thumbnaillocal Players = game:GetService("Players") |
|
|
| local player = Players.LocalPlayer |
|
|
| local PLACEHOLDER_IMAGE = "rbxassetid://0" -- replace with placeholder image |
|
|
| -- fetch the thumbnail |
| local userId = player.UserId |
| local thumbType = Enum.ThumbnailType.HeadShot |
| local thumbSize = Enum.ThumbnailSize.Size420x420 |
| local content, isReady = Players:GetUserThumbnailAsync(userId, thumbType, thumbSize) |
|
|
| -- set the ImageLabel's content to the user thumbnail |
| local imageLabel = script.Parent |
| imageLabel.Image = (isReady and content) or PLACEHOLDER_IMAGE |
| imageLabel.Size = UDim2.new(0, 420, 0, 420)Methods inherited from InstanceAddTagvoidThis method applies a tag to the instance, with no effect if the tag is |
| already applied. Successfully adding a tag will fire a signal created by |
| CollectionService:GetInstanceAddedSignal() with the given tag. |
| Note that when tagging an instance, it's common that some resources are |
| used to give the tag its functionality, for example event connections or |
| tables. To prevent memory leaks, it's a good idea to clean these up |
| (disconnect, set to nil, etc.) when no longer needed for a tag. Do this |
| when calling Instance:RemoveTag(), calling |
| Instance:Destroy(), or in a function connected to a signal |
| returned by CollectionService:GetInstanceRemovedSignal().Parameterstag: stringReturnsvoidClearAllChildrenvoidThis function destroys all of an Instance's children. |
| As Instance:Destroy() also calls itself on the children of an |
| object it is used on, this function will destroy all descendants. |
| Alternatives to ClearAllChildren |
| If the developer does not wish to destroy all descendants, they should use |
| Instance:GetChildren() or Instance:GetDescendants() to |
| loop through an object and select what to destroy. For example, the |
| following code sample will destroy all parts in an object. |
| for _, instance in pairs(object:GetDescendants()) do |
| if instance:IsA("BasePart") then |
| instance:Destroy() |
| end |
| endReturnsvoidCode SamplesThis example creates a Part and adds a few sparkle objects to the part. Then |
| it calls Part:ClearAllChildren() to remove all of the children.Instance:ClearAllChildrenlocal part = Instance.new("Part") |
|
|
| -- add some sparkles |
| for _ = 1, 3 do |
| local sparkles = Instance.new("Sparkles") |
| sparkles.Parent = part |
| end |
|
|
| print("Part has", #part:GetChildren(), "children") |
| --> Part has 3 children |
|
|
| part:ClearAllChildren() |
|
|
| print("Part has", #part:GetChildren(), "children") |
| --> Part has 0 childrenCloneInstanceClone creates a copy of an object and all of its descendants, ignoring |
| all objects that are not Archivable. The copy |
| of the root object is returned by this function and its |
| Parent is set to nil. |
| If a reference property such as ObjectValue.Value is set in a |
| cloned object, the value of the copy's property depends on original's |
| value: |
|
|
| If a reference property refers to an object that was also cloned, an |
| internal reference, the copy will refer to the copy. |
| If a reference property refers to an object that was not cloned, an |
| external reference, the same value is maintained in the copy. |
|
|
| This function is typically used to create models that can be regenerated. |
| First, get a reference to the original object. Then, make a copy of the |
| object and insert the copy by setting its Parent |
| to the Workspace or one of its descendants. Finally, when it's |
| time to regenerate the model, Destroy the copy |
| and clone a new one from the original like before.ReturnsInstanceCode SamplesThis code first references an existing object in the original variable. |
| Then, it makes a copy of the object, sets the parent to that of the original, |
| and finally moves the copy to (0, 50, 0).Clone Example-- Get a reference to an existing object |
| local original = workspace.Model |
| -- Create the model copy |
| local copy = original:Clone() |
| -- Parent the copy to the same parent as the original |
| copy.Parent = original.Parent |
| -- Move the copy so it's not overlapping the original |
| copy:SetPrimaryPartCFrame(CFrame.new(0, 50, 0))DestroyvoidSets the Instance.Parent property to nil, locks the |
| Instance.Parent property, disconnects all connections, and calls |
| Destroy on all children. This function is the correct way to dispose of |
| objects that are no longer required. Disposing of unneeded objects is |
| important, since unnecessary objects and connections in a place use up |
| memory (this is called a memory leak) which can lead to serious |
| performance issues over time. |
| Tip: After calling Destroy on an object, set any variables referencing |
| the object (or its descendants) to nil. This prevents your code from |
| accessing anything to do with the object. |
| local part = Instance.new("Part") |
| part.Name = "Hello, world" |
| part:Destroy() |
| -- Don't do this: |
| print(part.Name) --> "Hello, world" |
| -- Do this to prevent the above line from working: |
| part = nil |
| Once an Instance has been destroyed by this method it cannot be |
| reused because the Instance.Parent property is locked. To |
| temporarily remove an object, set Parent it to nil |
| instead. For example: |
| object.Parent = nil |
| wait(2) |
| object.Parent = workspace |
| To Destroy an object after a set amount of time, use |
| Debris:AddItem().ReturnsvoidCode SamplesInstance:Destroylocal Part = workspace.Part |
|
|
| Part:Destroy() |
|
|
| Part.Parent = workspace --> The Parent property of Part is lockedFindFirstAncestorInstanceWrite ParallelReturns the first ancestor of the Instance whose |
| Instance.Name is equal to the given name. |
| This function works upwards, meaning it starts at the Instance's |
| immediate Instance.Parent and works up towards the |
| DataModel. If no matching ancestor is found, it returns nil. |
| The following code snippet would find the first ancestor of the object |
| named 'Car'. |
| local car = object:FindFirstAncestor("Car") |
| For variants of this function that find ancestors of a specific class, |
| please see Instance:FindFirstAncestorOfClass() and |
| Instance:FindFirstAncestorWhichIsA().Parametersname: stringThe Instance.Name to be looked for.ReturnsInstanceThe Instance found.FindFirstAncestorOfClassInstanceWrite ParallelReturns the first ancestor of the Instance whose |
| Instance.ClassName is equal to the given className. |
| This function works upwards, meaning it starts at the Instance's |
| immediate Instance.Parent and works up towards the |
| DataModel. If no matching ancestor is found, it returns nil. |
| A common use of this function is finding the Model a |
| BasePart belongs to. For example: |
| local model = part:FindFirstAncestorOfClass("Model") |
| This function is a variant of Instance:FindFirstAncestor() which |
| checks the Instance.ClassName property rather than |
| Instance.Name. Instance:FindFirstAncestorWhichIsA() also |
| exists, using the Instance:IsA() method instead to respect class |
| inheritance.ParametersclassName: stringThe Instance.ClassName to be looked for.ReturnsInstanceThe Instance found.FindFirstAncestorWhichIsAInstanceWrite ParallelReturns the first ancestor of the Instance for whom |
| Instance:IsA() returns true for the given className. |
| This function works upwards, meaning it starts at the Instance's |
| immediate Instance.Parent and works up towards the |
| DataModel. If no matching ancestor is found, it returns nil. |
| Unlike Instance:FindFirstAncestorOfClass(), this function uses |
| Instance:IsA() which respects class inheritance. For example: |
| print(part:IsA("Part")) --> true |
| print(part:IsA("BasePart")) --> true |
| print(part:IsA("Instance")) --> true |
| Therefore, the following code sample will return the first |
| BasePart ancestor, regardless of if it is a WedgePart, |
| MeshPart or Part. |
| local part = object:FindFirstAncestorWhichIsA("BasePart") |
| See also, Instance:FindFirstAncestor().ParametersclassName: stringThe Instance.ClassName to be looked for.ReturnsInstanceThe Instance found.FindFirstChildInstanceWrite ParallelReturns the first child of the Instance with the given name, |
| or nil if no such child exists. If the optional recursive argument is |
| true, this function searches all descendants rather than only the |
| immediate children of the Instance. |
| Checking the Existence of an Object |
| FindFirstChild is necessary if you need to verify an object exists before |
| continuing. Attempting to index a child by name using the dot operator |
| throws an error if the child doesn't exist. |
| -- The following line errors if Part doesn't exist in the Workspace: |
| workspace.Part.Transparency = 0.5 |
| Use FindFirstChild to first check for Part, then use an if-statement to |
| run code that needs it. |
| local part = workspace:FindFirstChild("Part") |
| if part then |
| part.Transparency = 0.5 |
| end |
| Finding a Child Whose Name Matches a Property |
| Sometimes the Name of an object is the same as that |
| of a property of its Parent. When using the dot |
| operator, properties take precedence over children if they share a name. |
| In the following example, a Folder called "Color" is added to a |
| Part, which also has the Part.Color property. |
| Part.Color refers to the Color3, not the Folder. |
| local part = Instance.new("Part") |
| local folder = Instance.new("Folder") |
| folder.Name = "Color" |
| folder.Parent = part |
| local c = part.Color --> A Color3 |
| local c2 = part:FindFirstChild("Color") --> The Folder |
| A benefit of using FindFirstChild() in |
| this way is that the introduction of new properties does not impose a risk |
| on your code. |
| Performance Note |
| FindFirstChild() takes about 20% longer |
| than using the dot operator and almost 8 times longer than simply storing |
| a reference to an object. Therefore, you should avoid calling it in |
| performance-dependent code such as in tight loops or functions connected |
| to RunService.Heartbeat and RunService.RenderStepped. |
| Instead, store the result in a variable, or consider using |
| ChildAdded or |
| WaitForChild() to detect when a child of a |
| given name becomes available.Parametersname: stringThe Instance.Name to be searched for.recursive: booleanWhether or not the search should be conducted recursively.Default Value: falseReturnsInstanceThe Instance found.Code SamplesThe below would look in Workspace for an object name "Brick". If found, it |
| will change the name of the object to "Foo".Instance:FindFirstChildlocal found = workspace:FindFirstChild("Brick") |
|
|
| if found then |
| found.Name = "Foo" |
| endFindFirstChildOfClassInstanceWrite ParallelReturns the first child of the Instance whose |
| ClassName is equal to the given className. |
| If no matching child is found, this function returns nil. |
| Unlike Instance:FindFirstChildWhichIsA() this function uses only |
| returns objects whose class matches the given className, ignoring class |
| inheritance. |
| Developers looking for a child by name should use |
| Instance:FindFirstChild() instead.ParametersclassName: stringThe Instance.ClassName to be looked for.ReturnsInstanceThe Instance found.Code SamplesInstance:FindFirstChildOfClasslocal Players = game:GetService("Players") |
|
|
| local player = Players.LocalPlayer |
| local character = player.Character or player.CharacterAdded:Wait() |
|
|
| local humanoid |
|
|
| while not humanoid do |
| humanoid = character:FindFirstChildOfClass("Humanoid") |
| if not humanoid then |
| character.ChildAdded:Wait() |
| end |
| endFindFirstChildWhichIsAInstanceWrite ParallelReturns the first child of the Instance for whom |
| Instance:IsA() returns true for the given className. |
| If no matching child is found, this function returns nil. If the optional |
| recursive argument is true, this function searches all descendants rather |
| than only the immediate children of the Instance. |
| Unlike Instance:FindFirstChildOfClass(), this function uses |
| Instance:IsA() which respects class inheritance. For example: |
| print(part:IsA("Part")) --> true |
| print(part:IsA("BasePart")) --> true |
| print(part:IsA("Instance")) --> true |
| Therefore, the following code sample will return the first |
| BasePart child, regardless of if it is a WedgePart, |
| MeshPart or Part. |
| local part = object:FindFirstChildWhichIsA("BasePart") |
| Developers looking for a child by name, should use |
| Instance:FindFirstChild() instead.ParametersclassName: stringThe Instance.ClassName to be searched for.recursive: booleanWhether or not the search should be conducted recursively.Default Value: falseReturnsInstanceThe Instance found.FindFirstDescendantInstanceWrite ParallelReturns the first descendant found with the given Instance.Name.Parametersname: stringThe Instance.Name to search for.ReturnsInstanceThe Instance found.GetActorActorWrite ParallelIf the Instance is an Actor, the Actor itself is |
| returned. Otherwise, its closest ancestor Actor is returned. If no |
| ancestor is an Actor, the result is nil.ReturnsActorThe Actor found.GetAttributeVariantWrite ParallelThis function returns the attribute which has been assigned to the given |
| name. If no attribute has been assigned then nil is returned. |
| For example, the following code snippet will set the value of the |
| instance's InitialPostion attribute. Note that this code sample does not |
| define Instance: |
| local initialPosition = instance:GetAttribute("InitialPosition") |
| See also: |
|
|
| Instance:SetAttribute(), sets the attribute with the given name |
| to the given value |
| Instance:GetAttributes(), returns a dictionary of string → |
| variant pairs for each of the instance's attributes |
| Instance.AttributeChanged, fires whenever an attribute is |
| changed on the instance |
| Instance:GetAttributeChangedSignal(), returns an event that |
| fires when the given attribute changes |
| Parametersattribute: stringThe name of the attribute being retrieved.ReturnsVariantThe attribute which has been assigned to the given name. If no |
| attribute has been assigned then nil is returned.GetAttributeChangedSignalRBXScriptSignalThis function returns an event that behaves exactly like the Changed |
| event, except that the event only fires when the given attribute changes. |
| It's generally a good idea to use this method instead of a connection to |
| Changed with a function that checks the attribute name. Subsequent calls |
| to this method on the same object with the same attribute name return the |
| same event. |
| It is similar to Instance:GetPropertyChangedSignal() but for |
| attributes. |
| For example, the following code snippet will return a signal that fires |
| the function Instance.AttributeChanged when the instance's |
| InitialPosition attribute changes. Note that this code sample does not |
| define Instance: |
| local function attributeChanged() |
| print("Attribute changed") |
| end |
|
|
| instance:GetAttributeChangedSignal("InitialPosition"):Connect(attributeChanged) |
| See also: |
|
|
| Instance:SetAttribute(), sets the attribute with the given name |
| to the given value |
| Instance:GetAttribute(), returns the attribute which has been |
| assigned to the given name |
| Instance:GetAttributes(), returns a dictionary of string → |
| variant pairs for each of the instance's attributes |
| Instance.AttributeChanged, fires whenever an attribute is |
| changed on the instance |
| Parametersattribute: stringThe name of the specified attribute for which the change signal is |
| being returned.ReturnsRBXScriptSignalAn event that fires when the given attribute changes.GetAttributestableWrite ParallelThis function returns a dictionary of string → variant pairs for each |
| attribute where the string is the name of the attribute and the variant is |
| a non-nil value. |
| For example, the following code snippet will print an instance's |
| attributes and values. Note that this code sample does not define |
| Instance: |
| local attributes = instance:GetAttributes() |
| for name, value in pairs(attributes) do |
| print(name .. " " .. value) |
| end |
| See also: |
|
|
| Instance:SetAttribute(), sets the attribute with the given name |
| to the given value |
| Instance:GetAttribute(), returns the attribute which has been |
| assigned to the given name |
| Instance.AttributeChanged, fires whenever an attribute is |
| changed on the instance |
| Instance:GetAttributeChangedSignal(), returns an event that |
| fires when the given attribute changes |
| ReturnstableA dictionary of string → variant pairs for each attribute where the |
| string is the name of the attribute and the variant is a non-nil |
| value.GetChildrenObjectsWrite ParallelReturns an array (a numerically indexed table) containing all of the |
| Instance's direct children, or every Instance whose |
| Parent is equal to the object. The array can be |
| iterated upon using either a numeric or generic for-loop: |
| -- Numeric for-loop example |
| local children = workspace:GetChildren() |
| for i = 1, #children do |
| local child = children[i] |
| print(child.Name .. " is child number " .. i) |
| end |
| -- Generic for-loop example |
| local children = workspace:GetChildren() |
| for i, child in ipairs(children) do |
| print(child.Name .. " is child number " .. i) |
| end |
| The children are sorted by the order in which their |
| Parent property was set to the object. |
| See also the GetDescendants function.ReturnsObjectsAn array containing the Instance's children.Code SamplesThe below would print the name of all objects currently in Workspace when ran.Instance:GetChildrenlocal children = workspace:GetChildren() |
|
|
| for i = 1, #children do |
| print(i, children[i].Name) |
| endGetDebugIdstringNot BrowsablePlugin SecurityReturns a coded string of the Instances DebugId used internally by |
| Roblox. |
| Note: |
|
|
| This item is protected. Attempting to use it in a Script or |
| LocalScript will cause an error |
| A debug ID is an ID used in debugging processes. It allows a debugger to |
| read each instruction before an application processes it. All objects in |
| Roblox act like processes and each run instructions (or 'code') that can |
| be debugged if needed |
| This can be helpful for plugins which need to distinguish similar |
| objects from one-another (such as objects that share the same name) |
| ParametersscopeLength: numberThe scope length.Default Value: 4ReturnsstringThe Debug ID string.Code SamplesInstance:GetDebugIdprint(workspace:GetDebugId()) --> 39FA_12 |
| print(workspace:GetDebugId(10)) --> 39FA2FEF4D_12 |
| print(workspace:GetDebugId(math.huge)) --> 12GetDescendantsArrayCustom Lua StateWrite ParallelThe GetDescendants function of an object returns an array that |
| contains all of the descendants of that object. Unlike |
| Instance:GetChildren(), which only returns the immediate children |
| of an object, GetDescendants will find every child of the object, every |
| child of those children, and so on. |
| The arrays returned by GetDescendants are arranged so that parents come |
| earlier than their children. Refer to the following example of a |
| Model in the Workspace: |
|
|
| Inside this model are three parts (C, D, and E) and another model |
| (InnerModel). Inside the inner model are two more parts (A and B). Calling |
| GetDescendants on the first model and printing the contents of the |
| returned array would print the first level of children (InnerModel, C, D, |
| and E) before A and B. |
| local descendants = game.Workspace.Model:GetDescendants() |
|
|
| -- Loop through all of the descendants of the model and |
| -- print out their name |
| for index, descendant in pairs(descendants) do |
| print(descendant.Name) |
| end |
|
|
| -- Prints: |
| -- C |
| -- D |
| -- E |
| -- InnerModel |
| -- A |
| -- BReturnsArrayAn array containing the Instance's descendants.Code SamplesGetDescendants is often used to do something to all the descendants that are a |
| particular type of object. The code in this example uses GetDescendants and |
| Instance:IsA() to find all of the parts in the workspace and turns |
| them green.Instance:GetDescendantslocal descendants = workspace:GetDescendants() |
|
|
| -- Loop through all of the descendants of the Workspace. If a |
| -- BasePart is found, the code changes that parts color to green |
| for _, descendant in pairs(descendants) do |
| if descendant:IsA("BasePart") then |
| descendant.BrickColor = BrickColor.Green() |
| end |
| endGetFullNamestringWrite ParallelReturns a string describing the Instance's ancestry. The string is |
| a concatenation of the Name of the object and its |
| ancestors, separated by periods. The DataModel (game) is not |
| considered. For example, a Part in the Workspace may |
| return Workspace.Part. |
| When called on an Instance that is not a descendant of the |
| DataModel, this function considers all ancestors up to and |
| including the topmost one without a Parent. |
| This function is useful for logging and debugging. You shouldn't attempt |
| to parse the returned string for any useful operation; this function does |
| not escape periods (or any other symbol) in object names. In other words, |
| although its output often appears to be a valid Lua identifier, it is not |
| guaranteed.ReturnsstringThe full name of the Instance.Code SamplesThis code sample demonstrates the behavior of Instance:GetFullName(). |
| It shows how the function behaves when called on an object not in the |
| DataModel hierarchy, and it also shows how the return value does not escape |
| special characters.Instance:GetFullName-- Create a simple hierarchy |
| local model = Instance.new("Model") |
| local part = Instance.new("Part") |
| part.Parent = model |
| local fire = Instance.new("Fire") |
| fire.Parent = part |
|
|
| print(fire:GetFullName()) --> Model.Part.Fire |
|
|
| model.Parent = workspace |
|
|
| print(fire:GetFullName()) --> Workspace.Model.Part.Fire |
|
|
| part.Name = "Hello, world" |
|
|
| print(fire:GetFullName()) --> Workspace.Model.Hello, world.FireThis code sample re-implements the Instance:GetFullName() function in |
| Lua.Instance:GetFullName Lua Implementationlocal function getFullName(object) |
| local result = object.Name |
| object = object.Parent |
| while object and object ~= game do |
| -- Prepend parent name |
| result = object.Name .. "." .. result |
| -- Go up the hierarchy |
| object = object.Parent |
| end |
| return result |
| end |
|
|
| print(getFullName(workspace.Camera)) --> Workspace.CameraGetPropertyChangedSignalRBXScriptSignalThis method returns an event that behaves exactly like the Changed |
| event, except that the event only fires when the given property changes. |
| It's generally a good idea to use this method instead of a connection to |
| Changed with a function that checks the property name. Subsequent calls |
| to this method on the same object with the same property name return the |
| same event. |
| print(object:GetPropertyChangedSignal("Name") == object:GetPropertyChangedSignal("Name")) --> always true |
| ValueBase objects, such as IntValue and |
| StringValue, use a modified Changed event that fires with the |
| contents of the Value property. As such, this method provides a way to |
| detect changes in other properties of those objects. For example, to |
| detect changes in the Name property of an IntValue, use |
| IntValue:GetPropertyChangedSignal("Name"):Connect(someFunc) since the |
| Changed event of IntValue objects only detect changes on the |
| Value property.Parametersproperty: stringThe property to connect to.ReturnsRBXScriptSignalA signal that fires whenever the property changes.Code SamplesThis code sample demonstrates how to save a value before a changed event fires |
| on it in order to get more information about a change.Old-to-New Values with Changedlocal part = Instance.new("Part") |
|
|
| local currentColor = part.BrickColor |
|
|
| local function onBrickColorChanged() |
| local newColor = part.BrickColor |
| print("Color changed from", currentColor.Name, "to", newColor.Name) |
| currentColor = newColor |
| end |
| part:GetPropertyChangedSignal("BrickColor"):Connect(onBrickColorChanged) |
|
|
| part.BrickColor = BrickColor.new("Really red") |
| part.BrickColor = BrickColor.new("Really blue")This code sample demonstrates the equivalence of the Changed event and event |
| returned by GetPropertyChangedSignal.Changed and GetPropertyChangedSignallocal part = Instance.new("Part") |
|
|
| local function onBrickColorChanged() |
| print("My color is now " .. part.BrickColor.Name) |
| end |
|
|
| local function onChanged(property) |
| if property == "BrickColor" then |
| onBrickColorChanged() |
| end |
| end |
|
|
| part:GetPropertyChangedSignal("BrickColor"):Connect(onBrickColorChanged) |
| part.Changed:Connect(onChanged) |
|
|
| -- Trigger some changes (because we connected twice, |
| -- both of these will cause two calls to onBrickColorChanged) |
| part.BrickColor = BrickColor.new("Really red") |
| part.BrickColor = BrickColor.new("Institutional white")GetTagsArrayWrite ParallelThis method returns an array of the tags applied to the given instance, as |
| strings. You can add tags either in Studio in the |
| Properties window or at runtime with |
| AddTag(). |
| This method is useful when you want to do something with multiple tags on |
| an instance at once. However, it is inefficient to use this method to |
| check for the existence of a single tag; instead, use |
| HasTag() to check for a specific tag.ReturnsArrayHasTagbooleanWrite ParallelThis method returns true if the provided tag has been added to the |
| object. You can add tags either in Studio in the |
| Properties window or at runtime with |
| AddTag().Parameterstag: stringReturnsbooleanIsAbooleanCustom Lua StateWrite ParallelIsA returns true if the Instance's class is equivalent to or a |
| subclass of a given class. This function is similar to the |
| instanceof operators in other languages, and is a form of |
| type introspection. To |
| ignore class inheritance, test the ClassName |
| property directly instead. For checking native Lua data types (number, |
| string, etc) use the functions type and typeof. |
| Most commonly, this function is used to test if an object is some kind of |
| part, such as Part or WedgePart, which inherits from |
| BasePart (an abstract class). For example, if your goal is to |
| change all of a Character's limbs to the same |
| color, you might use GetChildren to iterate |
| over the children, then use IsA to filter non-BasePart objects |
| which lack the BrickColor property: |
| local function paintFigure(character, color) |
| -- Iterate over the child objects of the character |
| for _, child in pairs(character:GetChildren()) do |
| -- Filter out non-part objects, such as Shirt, Pants and Humanoid |
| -- R15 use MeshPart and R6 use Part, so we use BasePart here to detect both: |
| if child:IsA("BasePart") then |
| child.BrickColor = color |
| end |
| end |
| end |
| paintFigure(game.Players.Player.Character, BrickColor.new("Bright blue")) |
| Since all classes inherit from Instance, calling |
| object:IsA("Instance") will always return true.ParametersclassName: stringThe class against which the Instance's class will be checked. |
| Case-sensitive.ReturnsbooleanDescribes whether the Instance's class matched or is a subclass of the |
| given class.Code SamplesUsage of IsA to test class inheritance:Instance:IsAprint(workspace:IsA("Instance")) --> true |
| print(workspace:IsA("Workspace")) --> true |
| print(game:IsA("workspace")) --> false |
| print(game:IsA("DataModel")) --> trueIsAncestorOfbooleanWrite ParallelReturns true if an Instance is an ancestor of the given |
| descendant. |
| An Instance is considered the ancestor of an object if the |
| object's Instance.Parent or one of it's parent's |
| Instance.Parent is set to the Instance. |
| See also, Instance:IsDescendantOf().Parametersdescendant: InstanceThe descendant Instance.ReturnsbooleanTrue if the Instance is an ancestor of the given descendant.Code SamplesInstance:IsAncestorOfprint(workspace:IsAncestorOf(workspace.Player.HumanoidRootPart)) --> trueIsDescendantOfbooleanWrite ParallelReturns true if an Instance is a descendant of the given ancestor. |
| An Instance is considered the descendant of an object if the |
| Instance's parent or one of its parent's parent is set to the |
| object. |
| Note, DataModel is a descendant of nil. This means IsDescendantOf |
| cannot be used with a parameter of nil to check if an object has been |
| removed. |
| See also, Instance:IsAncestorOf().Parametersancestor: InstanceThe ancestor Instance.ReturnsbooleanTrue if the Instance is a descendant of the given ancestor.Code SamplesInstance:IsDescendantOflocal part = Instance.new("Part") |
| print(part:IsDescendantOf(game)) |
| --> false |
|
|
| part.Parent = workspace |
| print(part:IsDescendantOf(game)) |
| --> true |
|
|
| part.Parent = game |
| print(part:IsDescendantOf(game)) |
| --> trueRemovevoidDEPRECATEDDEPRECATEDThis item is deprecated in favor of Instance:Destroy() and |
| Instance:ClearAllChildren(). If you must remove an object from the |
| game, and wish to use the object later, set its Parent property to nil |
| instead of using this method.The Remove function sets the object's Instance.Parent to nil, and |
| does the same for all its descendants. |
| If the object is referenced before being removed it is possible to |
| retrieve the object at a later point.ReturnsvoidCode SamplesThe following code demonstrates how a part can be re-added to the DataModel |
| after being removed:Instance:Removelocal part = Instance.new("Part") |
| part.Parent = workspace |
| print(part.Parent) --> Workspace |
|
|
| part:Remove() |
|
|
| print(part.Parent) --> nil |
|
|
| part.Parent = workspace |
|
|
| print(part.Parent) --> WorkspaceRemoveTagvoidThis method removes a tag from an instance. It will not throw an error if |
| the object does not have the tag. Successfully removing a tag will fire a |
| signal created by CollectionService:GetInstanceRemovedSignal() |
| with the given tag. |
| Note that when tagging an instance, it's common that some resources are |
| used to give the tag its functionality, for example event connections or |
| tables. To prevent memory leaks, it's a good idea to clean these up |
| (disconnect, set to nil, etc.) when no longer needed for a tag.Parameterstag: stringReturnsvoidSetAttributevoidThis function sets the attribute with the given name to the given value. |
| If the value given is nil, then the attribute will be removed (since nil |
| is returned by default). |
| For example, the following code snippet will set the instance's |
| InitialPosition attribute to Vector3.new(0, 0, 0). |
| Note that this code sample does not define Instance: |
| instance:SetAttribute("InitialPosition", Vector3.new(0, 0, 0)) |
| Limitations |
| Naming requirements and restrictions: |
|
|
| Names must only use alphanumeric characters and underscore |
| No spaces or unique symbols are allowed |
| Strings must be 100 characters or less |
| Names are not allowed to start with RBX unless the caller is a Roblox |
| core-script (reserved for Roblox) |
|
|
| When attempting to set an attribute to an unsupported type, an error will |
| be thrown. |
| See also: |
|
|
| Instance:GetAttribute(), returns the attribute which has been |
| assigned to the given name |
| Instance:GetAttributes(), returns a dictionary of string → |
| variant pairs for each of the instance's attributes |
| Instance.AttributeChanged, fires whenever an attribute is |
| changed on the instance |
| Instance:GetAttributeChangedSignal(), returns an event that |
| fires when the given attribute changes |
| Parametersattribute: stringThe name of the attribute being set.value: VariantThe value that the specified attribute is being set to.ReturnsvoidWaitForChildInstanceCustom Lua StateCan YieldReturns the child of the Instance with the given name. If the |
| child does not exist, it will yield the current thread until it does. If |
| the timeOut parameter is specified, this method will time out after the |
| specified number of seconds and return nil. |
| Primary Usage |
| WaitForChild() is extremely important when |
| working on code run by the client in a LocalScript. The Roblox |
| engine does not guarantee the time or order in which objects are |
| replicated from the server to the client. Additionally, if an experience |
| has Workspace.StreamingEnabled set to true, |
| BaseParts that are far away from the player's character |
| may not be streamed to the client, potentially causing scripts to break |
| when indexing objects that do not yet exist on the client. |
| Notes |
|
|
|
|
| This function does not yield if a child with the given name exists when |
| the call is made. |
|
|
|
|
| Instance:FindFirstChild() is a more efficient alternative to |
| WaitForChild() for objects that are |
| assumed to exist. |
|
|
|
|
| If a call to this method exceeds 5 seconds without returning, and no |
| timeOut parameter has been specified, a warning will be printed to the |
| output that the thread may yield indefinitely. This warning takes the |
| following form where X is the parent's name and Y is the child's |
| name: |
| Infinite yield possible on 'X:WaitForChild("Y")' |
|
|
| ParameterschildName: stringThe Instance.Name to be looked for.timeOut: numberAn optional time out parameter.ReturnsInstanceThe Instance found.Code SamplesThe following code waits for an instance named "Part" to be added to |
| Workspace.Instance:WaitForChildlocal part = workspace:WaitForChild("Part") |
| print(part.Name .. " has been added to the Workspace")childrenObjectsDEPRECATEDDEPRECATEDThis item has been superseded by Instance:GetChildren() which |
| should be used in all new work.The children function returns an array of the object's children.ReturnsObjectsArray of child objects/instances.cloneInstanceDEPRECATEDDEPRECATEDThis deprecated function is a variant of Instance:Clone() which |
| should be used instead.ReturnsInstancedestroyvoidDEPRECATEDDEPRECATEDThis deprecated function is a variant of Instance:Destroy() which |
| should be used instead.ReturnsvoidfindFirstChildInstanceDEPRECATEDDEPRECATEDThis deprecated function is a variant of Instance:FindFirstChild() |
| which should be used instead.Parametersname: stringrecursive: booleanDefault Value: falseReturnsInstancegetChildrenObjectsDEPRECATEDDEPRECATEDThis deprecated function is a variant of Instance:GetChildren() |
| which should be used instead.ReturnsObjectsisAbooleanDEPRECATEDCustom Lua StateDEPRECATEDThis deprecated function is a variant of Instance:IsA() which |
| should be used instead.ParametersclassName: stringReturnsbooleanisDescendantOfbooleanDEPRECATEDDEPRECATEDThis deprecated function is a variant of Instance:IsDescendantOf() |
| which should be used instead.Parametersancestor: InstanceReturnsbooleanremovevoidDEPRECATEDDEPRECATEDThis deprecated function is a variant of Instance:Remove() which |
| has also been deprecated. Neither function should be used in new work.ReturnsvoidEventsPlayerAddedThe PlayerAdded event fires when a player enters the game. This is used to |
| fire an event when a player joins a game, such as loading the player's |
| saved GlobalDataStore data. |
| This can be used alongside the Players.PlayerRemoving event, which |
| fires when a player is about to leave the game. For instance, if you would |
| like print a message every time a new player joins or leaves the game: |
| local Players = game:GetService("Players") |
|
|
| Players.PlayerAdded:Connect(function(player) |
| print(player.Name .. " joined the game!") |
| end) |
|
|
| Players.PlayerRemoving:Connect(function(player) |
| print(player.Name .. " left the game!") |
| end) |
| If you want to track when a player's character is added or removed from |
| the game, such as when a player respawns or dies, you can use the |
| Player.CharacterAdded and Player.CharacterRemoving |
| functions. |
|
|
|
|
| Up until recently, this event didn't work on the client (in |
| Localscripts), but this has been changed |
|
|
|
|
| This event does not work as expected in solo mode, because the player |
| is created before scripts that connect to PlayerAdded run. To handle |
| this case, as well as cases in which the script is added into the game |
| after a player enters, create an OnPlayerAdded function that you can |
| call to handle a player's entrance. |
|
|
| Parametersplayer: PlayerAn instance of the player that joined the game.Code SamplesThis example will print "A player has entered: " followed by the name of the |
| player that enters/joins a game every time a player joins.Players.PlayerAddedlocal Players = game:GetService("Players") |
|
|
| local function onPlayerAdded(player) |
| print("A player has entered: " .. player.Name) |
| end |
|
|
| Players.PlayerAdded:Connect(onPlayerAdded)PlayerMembershipChangedThis event fires when the game server recognizes that a player's |
| membership has changed. Note, however, that the server will only attempt |
| to check and update the membership after the Premium modal has been |
| closed. Thus, to account for cases where the user purchases Premium |
| outside of the game while playing, you must still prompt them to |
| purchase Premium; this will then show a message telling them they're |
| already upgraded and, once they close the modal, the game server will |
| update their membership and trigger this event. |
| To learn more about and incorporating Premium into your experience and |
| monetizing with the engagement-based payouts system, see |
| Engagement-Based Payouts. |
| See also: |
|
|
| MarketplaceService:PromptPremiumPurchase(), used to prompt a |
| user to purchase Premium |
| MarketplaceService.PromptPremiumPurchaseFinished, fires when the |
| Premium purchase UI closes |
| Parametersplayer: PlayerCode SamplesThe function in the code sample runs after the game server confirms a player's |
| membership has changed. It demonstrates how you can grant players access to |
| Premium benefits (or revoke them) when their membership status changes.Handling Premium Membership Changeslocal Players = game:GetService("Players") |
|
|
| local function grantPremiumBenefits(player) |
| -- Grant the player access to Premium-only areas, items, or anything you can imagine! |
| print("Giving", player, "premium benefits!") |
| end |
|
|
| local function playerAdded(player) |
| if player.MembershipType == Enum.MembershipType.Premium then |
| grantPremiumBenefits(player) |
| end |
| end |
|
|
| local function playerMembershipChanged(player) |
| print("Received event PlayerMembershipChanged. New membership = " .. tostring(player.MembershipType)) |
| if player.MembershipType == Enum.MembershipType.Premium then |
| grantPremiumBenefits(player) |
| end |
| end |
|
|
| Players.PlayerAdded:Connect(playerAdded) |
| Players.PlayerMembershipChanged:Connect(playerMembershipChanged)PlayerRemovingThe PlayerRemoving event fires right before a Player leaves the |
| game. This event fires before ChildRemoved |
| does on Players, and behaves somewhat similarly to |
| Instance.DescendantRemoving. Since it fires before the actual |
| removal of a Player, this event is useful for storing player data |
| using a GlobalDataStore. |
| This can be used alongside the Player.PlayerAdded event, which |
| fires when a player joins the game. For instance, to print a message every |
| time a new player joins or leaves the game: |
| local Players = game:GetService("Players") |
|
|
| Players.PlayerAdded:Connect(function(player) |
| print(player.Name .. " joined the game!") |
| end) |
|
|
| Players.PlayerRemoving:Connect(function(player) |
| print(player.Name .. " left the game!") |
| end) |
| If you want to track when a player's character is added or removed from |
| the game, such as when a player respawns or dies, you can use the |
| Player.CharacterAdded and Player.CharacterRemoving |
| functions.Parametersplayer: PlayerAn instance of the player that is leaving the game.Code SamplesThis code will print "A player has left: ", followed by the player's name, |
| every time a player leaves:Players.PlayerRemovinglocal Players = game:GetService("Players") |
|
|
| local function onPlayerRemoving(player) |
| print("A player has left: " .. player.Name) |
| end |
|
|
| Players.PlayerRemoving:Connect(onPlayerRemoving)UserSubscriptionStatusChangedThis event fires when the game server recognizes that the user's status |
| for a certain subscription has changed. Note that the server only attempts |
| to check and update the status after the Subscription Purchase modal |
| has been closed. To account for cases in which the user purchases the |
| subscription outside of the game while playing, you must still prompt |
| them to purchase the subscription; the prompt shows a message telling the |
| user they're already subscribed, and after they close the modal, the game |
| server updates their subscription status and triggers this event. |
| Note: Only server scripts receive this event.Parametersuser: PlayerUser whose subscription status has changed.subscriptionId: stringThe ID of the subscription with a status change.Events inherited from InstanceAncestryChangedFires when the Instance.Parent property of the object or one of |
| its ancestors is changed. |
| This event includes two parameters, child and parent. Child refers |
| to the Instance whose Instance.Parent was actually |
| changed. Parent refers to this Instance's new |
| Instance.Parent. |
| You can use this event to track the deletion of an instance in Studio, |
| such as manual deletion in the Explorer or through a plugin. If you need |
| to detect when an instance is destroyed using Instance:Destroy(), |
| use the Instance.Destroying event instead.Parameterschild: InstanceThe Instance whose Instance.Parent has been changed.parent: InstanceThe new Instance.Parent of the Instance whose |
| Instance.Parent was changed.Code SamplesThe below example would print "Part is now a child of Model".Instance.AncestryChangedlocal part = Instance.new("Part") |
| part.Parent = workspace |
|
|
| local function onAncestryChanged(child, parent) |
| print(child.Name .. " is now a child of " .. parent.Name) |
| end |
|
|
| part.AncestryChanged:Connect(onAncestryChanged) |
|
|
| part.Parent = workspace.ModelAttributeChangedThis event fires whenever an attribute is changed on the instance. This |
| includes when an attribute is set to nil. The name of the attribute that |
| has been changed is passed to the connected function. |
| For example, the following code snippet will connect the |
| AttributeChanged function to fire whenever one of Instance's |
| attributes changes. Note that this code sample does not define |
| Instance: |
| local function attributeChanged(attributeName) |
| print(attributeName, "changed") |
| end |
|
|
| instance.AttributeChanged:Connect(attributeChanged) |
| See also: |
|
|
| Instance:SetAttribute(), sets the attribute with the given name |
| to the given value |
| Instance:GetAttribute(), returns the attribute which has been |
| assigned to the given name |
| Instance:GetAttributes(), returns a dictionary of string → |
| variant pairs for each of the instance's attributes |
| Instance:GetAttributeChangedSignal(), returns an event that |
| fires when the given attribute changes |
| Parametersattribute: stringThe name of the attribute that has been changed.ChangedThe Changed event fires right after most properties change on objects. It |
| is possible to find the present value of a changed property by using |
| object[property]. To get the value of a property before it changes, you |
| must have stored the value of the property before it changed. |
| If you are only interested in listening to the change of a specific |
| property, consider using the GetPropertyChangedSignal method instead to |
| get an event that only fires when a given property changes. |
| This event does not fire for physics-related changes, like when the |
| CFrame, Velocity, RotVelocity, Position, Orientation |
| and CFrame properties of a BasePart change due to |
| gravity. To detect changes in these properties, consider using a |
| physics-based event like RunService.Stepped or |
| BasePart.Touched. A while-true-do loop can also work. |
| For "-Value" objects, this event behaves differently: it only fires when |
| the Value property changes. See individual pages for IntValue, |
| StringValue, etc for more information. To detect other changes in |
| these objects, you must use GetPropertyChangedSignal instead.Parametersproperty: stringThe name of the property that changed.Code SamplesThis sample demonstrates the subtleties of the Changed event on normal objects |
| and "-Value" objects.Changed Event-- Demonstrate the Changed event by creating a Part |
| local part = Instance.new("Part") |
| part.Changed:Connect(print) |
| -- This fires Changed with "Transparency" |
| part.Transparency = 0.5 |
| -- Similarly, this fires Changed with "Number" |
| part.Name = "SomePart" |
| -- Since changing BrickColor will also change other |
| -- properties at the same time, this line fires Changed |
| -- with "BrickColor", "Color3" and "Color3uint16". |
| part.BrickColor = BrickColor.Red() |
|
|
| -- A NumberValue holds a double-precision floating-point number |
| local vNumber = Instance.new("NumberValue") |
| vNumber.Changed:Connect(print) |
| -- This fires Changed with 123.456 (not "Value") |
| vNumber.Value = 123.456 |
| -- This does not fire Changed |
| vNumber.Name = "SomeNumber" |
|
|
| -- A StringValue stores one string |
| local vString = Instance.new("StringValue") |
| vString.Changed:Connect(print) |
| -- This fires Changed with "Hello" (not "Value") |
| vString.Value = "Hello"This code sample demonstrates the Changed event firing within a parent object.Change Detectorlocal object = script.Parent |
|
|
| local function onChanged(property) |
| -- Get the current value of the property |
| local value = object[property] |
| -- Print a message saying what changed |
| print(object:GetFullName() .. "." .. property .. " (" .. typeof(value) .. ") changed to " .. tostring(value)) |
| end |
|
|
| object.Changed:Connect(onChanged) |
| -- Trigger a simple change in the object (add an underscore to the name) |
| object.Name = "_" .. object.NameChildAddedFires after an object is parented to this Instance. |
| Note, when using this function on a client to detect objects created by |
| the server it is necessary to use Instance:WaitForChild() when |
| indexing these object's descendants. This is because the object and its |
| descendants are not guaranteed to replicate from the server to the client |
| simultaneously. For example: |
| workspace.ChildAdded:Connect(function(child) |
| -- need to use WaitForChild as descendants may not have replicated yet |
| local head = child:WaitForChild("Head") |
| end) |
| Note, this function only works for immediate children of the |
| Instance. For a function that captures all descendants, use |
| Instance.DescendantAdded. |
| See also, Instance.ChildRemoved.Parameterschild: InstanceThe Instance that has been added.Code SamplesThis snippet prints the names of objects as they are added to the Workspace:Instance.ChildAddedlocal function onChildAdded(instance) |
| print(instance.Name .. " added to the workspace") |
| end |
|
|
| workspace.ChildAdded:Connect(onChildAdded) |
|
|
| local part = Instance.new("Part") |
| part.Parent = workspace --> Part added to the WorkspaceChildRemovedFires after a child is removed from this Instance. |
| Removed refers to when an object's parent is changed from this |
| Instance to something other than this Instance. Note, this |
| event will also fire when a child is destroyed (using |
| Instance:Destroy()) as the destroy function sets an object's |
| parent to nil. |
| This function only works for immediate children of the Instance. |
| For a function that captures all descendants, use |
| Instance.DescendantRemoving. |
| See also Instance.ChildAdded.Parameterschild: InstanceThe Instance that has been removed.Code SamplesThis snippet prints the names of objects as they are removed from the |
| Workspace:Instance.ChildRemovedlocal function onChildRemoved(instance) |
| print(instance.Name .. " removed from the workspace") |
| end |
|
|
| workspace.ChildRemoved:Connect(onChildRemoved) |
|
|
| local part = Instance.new("Part") |
| part.Parent = workspace |
|
|
| task.wait(2) |
|
|
| part:Destroy()DescendantAddedThe DescendantAdded event fires after a descendant is added to the |
| Instance. |
| As DescendantAdded fires for every descendant, parenting an object to the |
| Instance will fire the event for this object and all of its |
| descendants individually. |
| Developers only concerned with the immediate children of the |
| Instance should use Instance.ChildAdded instead. |
| See also Instance.DescendantRemoving.Parametersdescendant: InstanceThe Instance that has been added.Code SamplesThis following example will print the name of any object that is added to the |
| Workspace:Instance.DescendantAddedlocal function onDescendantAdded(descendant) |
| print(descendant) |
| end |
|
|
| workspace.DescendantAdded:Connect(onDescendantAdded) |
|
|
| local part = Instance.new("Part") |
| part.Parent = workspaceDescendantRemovingDescendantRemoving fires immediately before the |
| Parent of a descendant of the Instance |
| changes such that the object is no longer a descendant of the Instance. |
| Destroy and Remove |
| change an object's Parent to nil, so calling these on a descendant of an |
| object will therefore cause this event to fire. |
| Since this event fires before the descendant's removal, the Parent of the |
| descendant will be unchanged, i.e., it will still be a descendant at the |
| time of this event firing. If the descendant is also a child of the |
| object, It will also fire before ChildRemoved. There is no similar event |
| called "DescendantRemoved". |
| If a descendant has children, this event fires with the descendant first |
| followed by its descendants. |
| Example |
| The example below should help clarify how DescendantRemoving fires when |
| there are several objects involved. |
|
|
|
|
| Calling Remove on PartA would cause |
| DescendantRemoving to fire on both ModelA and Model, in that |
| order. |
| Setting the Parent of PartA to ModelB |
| would cause DescendantRemoving to fire on ModelA but not Model |
| (as Model would still be an ancestor of PartA). |
| Calling Destroy on ModelA would cause |
| DescendantRemoving to fire multiple times on several objects: |
|
|
| On Model with ModelA, PartA then FireA. |
| On ModelA, with PartA then FireA. |
| On PartA with FireA. |
|
|
|
|
|
|
| Warning |
| This event fires with the descendant object that is being removed. |
| Attempting to set the Parent of the descendant |
| being removed to something else will fail with the following warning: |
| "Something unexpectedly tried to set the parent of X to Y while trying to |
| set the parent of X. Current parent is Z", where X is the removing |
| descendant, Y is the ignored parent setting, and Z is the original parent |
| of X. Below is an example that demonstrates this: |
| workspace.DescendantRemoving:Connect(function(descendant) |
| -- Don't manipulate the parent of descendant in this function! |
| -- This event fires BECAUSE the parent of descendant was manipulated, |
| -- and the change hasn't happened yet, i.e. this function fires before that happens. |
| -- Therefore, it is problematic to change the parent like this: |
| descendant.Parent = game |
| end) |
| local part = Instance.new("Part") |
| part.Parent = workspace |
| part.Parent = nil -- This triggers DescendantRemoving on Workspace: |
| --> Something unexpectedly tried to set the parent of Part to NULL while trying to set the parent of Part. Current parent is Workspace. |
| See also DescendantAdded.Parametersdescendant: InstanceThe Instance that is being removed.Code SamplesThe following example prints the name of any descendant as it is being removed |
| from the Workspace:Instance.DescendantRemovingworkspace.DescendantRemoving:Connect(function(descendant) |
| print(descendant.Name .. " is currently parented to " .. tostring(descendant.Parent)) |
| end) |
| local part = Instance.new("Part") |
| part.Parent = workspace |
| part.Parent = nil |
| --> Part is currently parented to Workspace |
| print(part.Parent) |
| --> nilDestroyingThe Destroying event fires immediately before the Instance or one of its |
| ancestors is destroyed with Instance.Destroy(). |
| The Instance will never be deleted from memory while a connected function |
| is still using it. However, if the function yields at any point, the |
| Instance and its descendants will be parented to nil. |
| When deleting an instance in Studio, such as manually deleting through the |
| Explorer or through a plugin, the instance isn't destroyed. Instead, the |
| parent is set to nil which you can track with |
| Instance.AncestryChanged.Code SamplesThis sample demonstrates how an Instance being destroyed remains in place |
| until the connected function yields.Using the Destroying Eventlocal part = Instance.new("Part", workspace) |
| |
| local function onPartDestroying() |
| print("Before yielding:", part:GetFullName(), #part:GetChildren()) |
| task.wait() |
| print("After yielding:", part:GetFullName(), #part:GetChildren()) |
| end |
| |
| part.Destroying:Connect(onPartDestroying) |
| |
| part:Destroy()childAddedDEPRECATEDDEPRECATEDThis deprecated event is a variant of Instance.ChildAdded which |
| should be used instead.Parameterschild: Instance |