Skip to content

Entities

Everything in a place is an Entity: a part, a light, a sound, a character, a button. Each entity has a name, a parent, children, and components that hold its data. This page covers how a script finds entities, moves them, creates and copies them, removes them, and gives them components.

The place tree

Entities form one tree per place. The top of the tree is World, and the entities directly under it have World as their Parent. Every other entity has another entity as its parent, and a child moves with its parent: moving a part moves every part under it.

The server and each client have their own world. The server's changes reach the clients in the next network update. An entity that a client script spawns or clones exists only on that client, which suits effects such as debris or a model in a viewport.

Find an entity

By name

Reading a name on an entity returns its property, method or component, never a child, and a name that matches nothing is an error. To get a child, call Find with its name, which returns nil when no child has that name:

-- Server script in a part.
local lid = self:Find("Lid")
if lid then
    lid.Transparency = { Transparency = 1 }
end

World.Find searches the top of the place and takes a slash-separated path such as "Arena/Gate". World.FindDescendant searches every level for the first entity with a name. To walk the tree, call Children on an entity, or World.Children and World.Descendants. Look an entity up once when the script loads and keep the reference, rather than searching again in every Update.

Wait for an entity from the server

A client script starts before the server's entities have all arrived. Use World.WaitFor, or WaitFor on an entity, for anything the server creates:

-- Client script.
local arena = World.WaitFor("Arena", 10)
if arena then
    local gate = arena:WaitFor("Gate", 10)
    print(gate ~= nil)
end

The script pauses until the entity exists and gets it back, or gets nil when the seconds run out. With a path, only the last name waits: while Arena is missing, World.WaitFor("Arena/Gate", 10) returns nil at once, so wait for each level in turn as above. A global Update declared after the script's first wait never runs, so declare Update before you call WaitFor.

Move an entity

Assign Parent to move an entity under another one, or assign World to move it to the top of the place. The entity keeps its position and rotation in the world, and its offset from the new parent changes to match:

-- Server script in a car body part.
local wheel = World.Find("Wheel")
if wheel then
    wheel.Parent = self
end

Assigning nil to Parent is an error. A client script cannot write Parent on an entity the server owns; see Network authority and replication.

To take an entity out of the game for a while and bring it back later, as in an object pool, add the Detached tag instead of moving it; see Detaching an entity.

Create an entity

World.Spawn creates an entity at the top of the place from a table of its components and their values, and returns it:

-- Server script: build a staircase of five steps.
for height = 1, 5 do
    local step = World.Spawn({
        Shape = "Box",
        Position = Vector3.new(0, height, height * 2),
    })
    step.Name = "Step"
    step.Size = Vector3.new(4, 1, 2)
end

World.Spawn({}) makes an empty entity that shows nothing until you add components to it. When the new entity goes under another parent, set its components and properties first and Parent last.

Spawn a prefab

A prefab is a saved tree of entities, exported from Studio with File > Export Selection.... Prefabs.Spawn creates a copy at the top of the place and returns its root. An optional second argument sets fields on the root, such as its Position. Spawn raises an error when no prefab has that name; check first with Prefabs.Exists when the prefab may be missing. On a client, Spawn spawns only platform prefabs and raises an error for the place's own prefabs.

-- Server script.
if Prefabs.Exists("TreasureChest") then
    local chest = Prefabs.Spawn("TreasureChest", {
        Position = Vector3.new(0, 2, 10),
    })
    print(chest.Name)
end

Clone an entity

Clone copies an entity and all its descendants. The copy has no parent until you set its Parent:

-- Server script in a part with a child named Template.
local template = self:Find("Template")
if template then
    local copy = template:Clone()
    copy.Parent = World
    local pos = self.Position
    if pos then
        copy.Position = pos + Vector3.new(0, 5, 0)
    end
end

The copy keeps the components and tags of the original. A cloned character belongs to no player.

Cloning the entity a script runs on

Every script attached to the original also runs in the copy, with self set to the copy. A script that clones its own self when it starts therefore runs again in the clone and clones again.

Destroy an entity

Destroy deletes an entity and all its descendants at once:

-- Server script in a part: the part disappears when something touches it.
self:On(Component.Collider.Touched, function()
    self:Destroy()
end)

Destroying an entity also:

  • disconnects every signal connection on the entity and its descendants;
  • stops the scripts attached to them;
  • fires ChildRemoved on the old parent;
  • removes the entities from every client in the next network update.

Calling Destroy again does nothing. A client script cannot destroy an entity the server owns and gets an error instead; send a Net message and let the server destroy it.

A script can still hold a destroyed entity and use it as a table key, but reading, writing or calling a member raises an error such as Entity: cannot index a destroyed Entity; Engine errors lists every message. Parent on a destroyed entity reads nil, and IsAlive returns false, so check target:IsAlive() before using a reference that may be stale.

To clean up when an entity goes away, connect Entity.Destroyed with the entity's On method from another script, such as the one that spawned it. The handler runs once, after the entity is destroyed:

-- Server script.
local coin = World.Spawn({ Shape = "Box" })
coin:On(Entity.Destroyed, function()
    print("coin removed")
end)

Remove an entity after a delay

Set an entity's Lifetime to the number of seconds it should live. The engine counts it down and destroys the entity and everything under it when it reaches zero:

-- Server script: a brick that disappears after 5 seconds.
local brick = World.Spawn({ Shape = "Box", Lifetime = 5 })

A client counts down only the entities it made.

Components

An entity's components decide what it is and hold its data: a part has transform, mesh and collision components, a light has Light, a sound has Sound. Add a component with Add, test for it with Has and take it away with Remove, passing a handle from the Component namespace. Indexing an entity with the name of a component that has several fields returns a view of those fields, or nil when the entity does not have the component. A single-value component such as Lifetime, Color or Position returns its value instead of a view:

-- Server script in a part.
self:Add(Component.Light)
local light = self.Light
if light then
    light.Intensity = 2
    light.Range = 20
end
print(self:Has(Component.Light)) -- prints true

Entity properties and components covers which properties read and write directly on the entity, and Component views lists the fields of every view.

To store your own values on an entity, define a component with World.DefineComponent and add it. Add returns the view of the new component. A component with no fields is a tag, which marks an entity without holding a value; World.Query finds every entity that has it:

-- Server script in a part.
local Coin = World.DefineComponent("Coin", {
    Worth = 1,
})
local Shiny = World.DefineComponent("Shiny")

local coin = self:Add(Coin)
coin.Worth = 5
self:Add(Shiny)

for entity in World.Query(Shiny) do
    print(entity.Name)
end

How it works

The server and each client keep their own copy of the tree. The server sends each change to a replicated component to the clients in its next network update, and a client that joins later gets the current values. A client script may write properties of any entity, but the write stays on that client.

Clone and Prefabs.Spawn give every copied entity a new ID. An entity that a client creates never reaches the server or the other clients. This is why a Field.Entity field in a Net message reads nil on the receiving side when the entity was destroyed or exists only on the sender's client.