Scripting API
Everything a script can call, in Lua and in TypeScript. Pick a language in any tab and every page follows. A TypeScript script is compiled to Lua and calls the same functions: see TypeScript for how it is written. This file is generated from the bindings in ScriptEngine.cpp: do not edit it by hand. After changing a binding, run the unit tests with CAIRN_UPDATE_DOCS=1 to rewrite it.
Script files
A script is a .lua file that ends by returning a table, or in a TypeScript project a .ts file that ends with export = DefineScript({ ... }). The engine makes one copy of that table's behaviour for each entity the script is on, and calls these functions on it if they exist. Inside them, self.Entity is the entity.
OnCreate(): when the scene starts or the entity is cloned. Every script's OnCreate runs before any OnStart.OnStart(): after every OnCreate.OnUpdate(deltaTime): every frame, with the seconds of game time since the last one.OnFixedUpdate(step): 60 times per second of game time, for physics and anything that must not depend on the frame rate.OnDestroy(): when the entity is destroyed or the scene stops.OnCollisionEnter(other, contact),OnCollisionStay(other, contact),OnCollisionExit(other, contact): when the entity's body starts touching another, on every fixed step it still does, and when they part.otheris the other entity.contact.Pointis where they touch andcontact.Normalpoints away from the other body. Both are zero on exit. No exit is sent when the other entity was destroyed.OnTriggerEnter(other, contact),OnTriggerStay(other, contact),OnTriggerExit(other, contact): the same, when either body is a trigger. Both entities are told.
A table named Fields in the script lists values the editor can set per entity. A field is a number, a boolean, a string or a Vec3, and is read as self.FieldName.
An error in a script is logged with its file and line. A script whose update fails is switched off until the scene restarts. Scripts cannot use io or os, and require reaches the project's own scripts only.
Vec3
A 3D vector. Make one with Vec3(x, y, z), Vec3(value) for all three the same, or Vec3() for zero. Supports +, -, * and / with numbers and other vectors, unary minus and ==.
x (number): The X component.y (number): The Y component.z (number): The Z component.v:Length() -> number: The length of the vector.v:Normalized() -> Vec3: The vector scaled to length 1. The zero vector stays zero.a:Dot(b: Vec3) -> number: The dot product.a:Cross(b: Vec3) -> Vec3: The cross product.a:Distance(b: Vec3) -> number: The distance between two points.Vec3.Lerp(a: Vec3, b: Vec3, t: number) -> Vec3: The point a fraction t of the way from a to b.v:Flat() -> Vec3: The vector with its Y set to 0: its part along the ground. For walking where something points without going up or down.Vec3.Zero (Vec3, read only): (0, 0, 0).Vec3.One (Vec3, read only): (1, 1, 1). The scale of something at its own size.Vec3.Up (Vec3, read only): (0, 1, 0).Vec3.Down (Vec3, read only): (0, -1, 0). The way things fall.Vec3.Forward (Vec3, read only): (0, 0, -1). The way an entity that is not turned faces.Vec3.Back (Vec3, read only): (0, 0, 1).Vec3.Right (Vec3, read only): (1, 0, 0).Vec3.Left (Vec3, read only): (-1, 0, 0).
Entity
An entity in the running scene. A script's own entity is self.Entity. Using an entity after it was destroyed is an error. Check with IsValid() when unsure. A component is a field of its name: entity.Rigidbody is the entity's Rigidbody, or nil when it has none.
entity:IsValid() -> boolean: False once the entity has been destroyed.Name (string): The entity's name.Tag (string): The entity's tag, for finding groups of entities with Scene.FindByTag.Persistent (boolean): Set on an entity at the top of the hierarchy, it stays, with everything under it and with its scripts still running, when Scene.Load switches to another scene. For a player, a score keeper, music that plays on.Active (boolean): Off, the entity and everything under it is as good as not there: not drawn, no physics body, no sound, and its scripts get no OnUpdate or OnFixedUpdate. It keeps its place and its values, and comes back as it was. Timers a script started keep running. Reading gives what was set on this entity itself: see ActiveInScene.ActiveInScene (boolean, read only): Whether the entity is really on: itself, and every entity above it. An entity that is on under a parent that is off is off.Layer (integer): The entity's layer, an index into the project's layer list.Position (Vec3): The position relative to the parent. Reading gives a copy: to change one axis, read it, change it and assign it back.Rotation (Vec3): The rotation relative to the parent, as angles in degrees about X, Y and Z. Reading gives a copy.Scale (Vec3): The scale relative to the parent. Reading gives a copy.WorldPosition (Vec3, read only): The position in the world, with every parent's transform applied.Forward (Vec3, read only): The direction the entity faces in the world (its -Z axis), length 1.Right (Vec3, read only): The entity's right (+X axis) in the world, length 1.Up (Vec3, read only): The entity's up (+Y axis) in the world, length 1.Parent (Entity?): The parent, or nil for an entity at the root. Assign an entity to move this one under it, or nil to move it to the root. Making an entity its own ancestor is an error.Children (Entity[], read only): The entity's children, in order.entity:Move(offset: Vec3|number, y?: number, z?: number): Moves the entity by this much from where it is: entity:Move(Vec3(0, 1, 0)), or entity:Move(0, 1, 0). The short way to change one axis.entity:Turn(degrees: Vec3|number, y?: number, z?: number): Turns the entity by this many degrees about X, Y and Z from how it is turned: entity:Turn(0, 90 * deltaTime, 0) spins it about its upright axis.entity:LookAt(target: Vec3|Entity): Turns the entity to face a point in the world, or another entity. Its -Z axis ends up pointing at the target.entity:Face(direction: Vec3): Turns the entity to face along a direction in the world. For a character that should look the way it walks: entity:Face(velocity:Flat()). A zero direction changes nothing.entity:FindChild(name: string) -> Entity?: The first child with this name. Looks at direct children only.entity:Destroy(delay?: number): Destroys the entity and everything under it at the end of the current update, after their OnDestroy has run. Until then it is still valid. With a delay, in seconds of game time, it happens that much later: burst:Destroy(1.5).entity:HasComponent(name: string) -> boolean: Whether the entity has the component with this name, such as "Camera" or "PointLight".entity:GetComponent(name: string) -> any: The entity's component with this name, or nil when it has none. The sections below list each component's fields.entity:AddComponent(name: string) -> any: Adds the component with this name and returns it. Returns the existing one when the entity already has it.entity:RemoveComponent(name: string): Removes the component with this name. Does nothing when the entity has none.entity:GetScript(name: string) -> table?: The entity's script with this file name (without ".lua" or ".ts"), which is the table its functions get as self. Call its functions and read its values directly.entity:SendMessage(functionName: string, ...: any) -> integer: Calls the function with this name on every script of the entity that has one, passing the extra arguments. Returns how many scripts had it.
AssetHandle
Names an asset: a mesh, material, texture or other file in the project. Get one from Assets.Find or from a component, and assign it to a component.
handle:IsValid() -> boolean: False for the empty handle, which names nothing.
Camera
Component: the view the scene is drawn from. Looks down the entity's -Z axis.
Projection (string): "Perspective" or "Orthographic".FieldOfView (number): Vertical field of view in degrees. Perspective only.OrthographicSize (number): Height of the view in world units. Orthographic only.NearClip (number): Nothing nearer than this is drawn.FarClip (number): Nothing further than this is drawn.Primary (boolean): The scene is drawn from the first primary camera.camera:ScreenToRay(x: number, y: number) -> Vec3, Vec3: The ray from the camera through a point of the picture, from (0, 0) at the top left to (1, 1) at the bottom right: where Input.GetViewPosition says the mouse is. Give both to Physics.Raycast to find what is under the mouse.camera:ScreenToGround(x: number, y: number, height?: number) -> Vec3?: Where the ray through a point of the picture meets flat ground at a height (0 when left out). nil when it never does, as when looking at the sky. For moving or aiming at where the mouse points.camera:WorldToScreen(point: Vec3) -> number, number, boolean: Where a point of the world is in the picture, counted as ScreenToRay counts, and whether it is in front of the camera. For a marker or a name drawn over something.
MeshRenderer
Component: draws a mesh with one material per part of the mesh.
Mesh (AssetHandle): The mesh to draw.Assets.Cube,Assets.SphereandAssets.Planeare built in.renderer:GetMaterial(slot: integer) -> AssetHandle: The material in a slot, counting from 1. The empty handle when the slot has none.renderer:SetMaterial(slot: integer, handle: AssetHandle): Puts a material in a slot, counting from 1.
DirectionalLight
Component: light from far away, such as the sun. Shines along the entity's -Z axis.
Color (Vec3): Linear RGB.Intensity (number): Brightness. 3 is a bright day.CastShadows (boolean): Only the first shadow-casting directional light casts shadows.
PointLight
Component: light in every direction from the entity's position.
Color (Vec3): Linear RGB.Intensity (number): Brightness.Range (number): How far the light reaches, in world units.CastShadows (boolean): Costs six shadow maps. Two point lights can cast shadows at once.
SpotLight
Component: a cone of light along the entity's -Z axis.
Color (Vec3): Linear RGB.Intensity (number): Brightness.Range (number): How far the light reaches, in world units.InnerAngle (number): Full angle in degrees of the cone that is lit at full strength.OuterAngle (number): Full angle in degrees of the cone where the light has faded to nothing.CastShadows (boolean): Costs one shadow map.
Sky
Component: an HDR image drawn as the background, which also lights the scene.
Environment (AssetHandle): An equirectangular .hdr image.Intensity (number): Brightness of the sky and of its light.Rotation (number): Turns the sky about the Y axis, in degrees.
Rigidbody
Component: makes the entity a physics body. Its shape comes from the collider components on the same entity. The body exists from the first fixed update after the component was added.
Type (string): "Static" never moves. "Dynamic" is moved by gravity, forces and collisions. "Kinematic" is moved by its entity's transform and pushes dynamic bodies.Mass (number): Kilograms. Dynamic bodies only.Friction (number): 0 is ice, 1 is rubber on concrete.Restitution (number): Bounciness, from 0 (none) to 1 (bounces back to where it fell from).LinearDamping (number): How quickly movement dies away on its own.AngularDamping (number): How quickly spin dies away on its own.GravityScale (number): Multiplies gravity for this body. 0 floats.body:GetVelocity() -> Vec3: How fast the body is moving, in units per second.body:SetVelocity(velocity: Vec3): Sets how fast the body is moving. For a jump, set the Y of the current velocity.body:GetAngularVelocity() -> Vec3: How fast the body is spinning: the axis it spins about, with radians per second as its length.body:SetAngularVelocity(velocity: Vec3): Sets how fast the body is spinning.body:AddForce(force: Vec3): Pushes the body with a force in newtons for one fixed step. Call it in OnFixedUpdate for a steady push. Dynamic bodies only.body:AddImpulse(impulse: Vec3): Changes the body's momentum at once: a hit, a kick. Dynamic bodies only.
BoxCollider
Component: a box shape for physics. Sizes are in the entity's own space and follow its scale. Without a Rigidbody on the entity it is a static body.
Size (Vec3): Full width, height and depth.Center (Vec3): Where the box sits relative to the entity.IsTrigger (boolean): A trigger reports what enters it and blocks nothing.
SphereCollider
Component: a sphere shape for physics.
Radius (number): The sphere's radius.Center (Vec3): Where the sphere sits relative to the entity.IsTrigger (boolean): A trigger reports what enters it and blocks nothing.
CapsuleCollider
Component: an upright capsule shape for physics, the usual shape for a character.
Radius (number): The capsule's radius.Height (number): From tip to tip, including both round ends.Center (Vec3): Where the capsule sits relative to the entity.IsTrigger (boolean): A trigger reports what enters it and blocks nothing.
MeshCollider
Component: a physics shape taken from a mesh. It follows the entity's scale.
Mesh (AssetHandle): The mesh to take the shape from. Left unset, it is the mesh of the entity's MeshRenderer.Convex (boolean): True wraps the mesh in its convex hull, which is cheap and the only kind a moving body can have. False uses the exact triangles, for level geometry that stays put.IsTrigger (boolean): A trigger reports what enters it and blocks nothing.
Joint
Component: ties the entity's body to another body, or to the world. The entity needs a Rigidbody and a collider. Changing a value makes the joint again from where the bodies are at that moment.
Type (string): "Fixed" welds the two together. "Hinge" lets them turn about Axis through Anchor. "Distance" keeps Anchor and ConnectedAnchor between MinDistance and MaxDistance apart.joint:GetConnectedEntity() -> Entity?: The entity whose body this one is tied to, or nil when it is tied to the world.joint:SetConnectedEntity(entity: Entity?): Ties the body to another entity's body, or to the world when given nil.Anchor (Vec3): Where the joint sits, relative to this entity.ConnectedAnchor (Vec3): Distance only: the point on the other body, relative to the connected entity, or a point in the world when tied to the world.Axis (Vec3): Hinge only: the direction of the axis to turn about, relative to this entity.MinDistance (number): Distance only: the least the two points may be apart. Negative means the distance they start at.MaxDistance (number): Distance only: the most the two points may be apart. Negative means the distance they start at.
CharacterController
Component: moves the entity as a game character does. It walks along the ground, climbs steps and gentle slopes, slides along walls and never falls over. Its shape is an upright capsule, and colliders or a Rigidbody on the same entity are not used. The character exists from the first fixed update after the component was added.
Radius (number): The capsule's radius.Height (number): From tip to tip, including both round ends.Center (Vec3): Where the capsule sits relative to the entity. With the entity at the character's feet this is half the height, straight up.SlopeLimit (number): The steepest ground it can walk up, in degrees from flat.StepHeight (number): The tallest ledge it walks up without jumping.Mass (number): Kilograms. Decides how hard it pushes dynamic bodies.GravityScale (number): Multiplies gravity for this character. 0 floats.controller:Move(velocity: Vec3): Sets the speed it walks at, in units per second. It keeps walking until told otherwise, so pass Vec3(0, 0, 0) to stop. Y is ignored: gravity and Jump own the vertical.controller:Jump(speed: number) -> boolean: Leaves the ground at this upward speed. Does nothing and returns false in the air.controller:IsGrounded() -> boolean: Whether it stood on ground it can stand on at the last fixed update.controller:GetVelocity() -> Vec3: How fast it really moved at the last fixed update, which is less than asked when a wall was in the way.
Physics
Questions about, and settings of, the physics world.
Physics.Raycast(origin: Vec3, direction: Vec3, maxDistance: number, ignore?: Entity) -> RaycastHit?: The nearest body along a ray, or nil when it hits nothing. A hit is a table with Entity, Point, Normal (pointing away from the surface) and Distance. ignore is optional: an entity the ray passes through. A ray from an entity's own position starts inside its collider, so pass self.Entity there.Physics.SphereCast(origin: Vec3, radius: number, direction: Vec3, maxDistance: number, ignore?: Entity) -> RaycastHit?: Moves a sphere along a ray and returns the first body it would touch, as Raycast does. Distance is how far the sphere's centre travels. Good for asking whether something of a given size fits through.Physics.BoxCast(origin: Vec3, halfExtents: Vec3, direction: Vec3, maxDistance: number, ignore?: Entity) -> RaycastHit?: The same with a box that is not turned. halfExtents is half its size on each axis.Physics.OverlapSphere(center: Vec3, radius: number) -> Entity[]: Every entity whose body touches a sphere placed in the world. Triggers are included. For an explosion's reach, or what is near the player.Physics.OverlapBox(center: Vec3, halfExtents: Vec3) -> Entity[]: The same with a box that is not turned.Physics.GetLayerCollision(layerA: integer, layerB: integer) -> boolean: Whether bodies on these two layers collide. A body's layer is its entity's Layer.Physics.SetLayerCollision(layerA: integer, layerB: integer, collide: boolean): Makes bodies on two layers collide or pass through each other from now on. The project's own settings come back when the game restarts.Physics.GetGravity() -> Vec3: The acceleration of gravity. (0, -9.81, 0) unless changed.Physics.SetGravity(gravity: Vec3): Changes gravity for every body.
Scene
The running scene.
Scene.GetName() -> string: The scene's name.Scene.FindByName(name: string) -> Entity?: The first entity with this name, in hierarchy order.Scene.Find(name: string) -> Entity: The first entity with this name. An error when there is none, which is what to want for something the script cannot do without: a typo in the name is caught here and not as a nil further on.Scene.FindByTag(tag: string) -> Entity[]: Every entity with this tag, in hierarchy order.Scene.FindWithComponent(name: string) -> Entity[]: Every entity that has the component with this name, in hierarchy order.Scene.CreateEntity(name?: string) -> Entity: Adds an empty entity at the root. The name may be left out.Scene.Load(scene: AssetHandle): Switches to another scene at the end of this frame: every entity goes, with OnDestroy, except the ones marked Persistent, and the new scene's entities come in and start. Get the scene with Assets.Find. An entity that stayed is not made a second time when a scene that has it is loaded again.Scene.LoadAdditive(scene: AssetHandle): Adds another scene's entities to the running scene at the end of this frame, leaving what is there. For a level made of parts, or a menu over the game.Scene.Unload(scene: AssetHandle): Removes, at the end of this frame, the entities that Scene.LoadAdditive added for that scene.Scene.GetCurrent() -> AssetHandle: The scene that is running: the one last given to Scene.Load, or the one the game started with. Scene.Load(Scene.GetCurrent()) starts the level over.Scene.Instantiate(prefab: AssetHandle, position?: Vec3, rotation?: Vec3) -> Entity: Places an instance of a prefab in the scene and returns its top entity. position and rotation (degrees) are optional: left out, it is where the prefab was saved. Get the prefab with Assets.Find. Its scripts get OnCreate and OnStart before this returns.Scene.Clone(entity: Entity) -> Entity: Copies an entity with everything under it, components, scripts and field values. The copy has the same parent. Its scripts get OnCreate and OnStart before this returns.
Assets
Finds assets in the project. Assets.Cube, Assets.Sphere and Assets.Plane are the built-in meshes.
Assets.Cube (AssetHandle, read only): The built-in cube mesh, one unit on each side.Assets.Sphere (AssetHandle, read only): The built-in sphere mesh, one unit across.Assets.Plane (AssetHandle, read only): The built-in plane mesh: a square one unit across, facing up.Assets.Find(path: string, part?: string) -> AssetHandle: The asset at a path inside the project, such as "Assets/Materials/Gold.cairnmat". For something inside a model, give the part too, such as "Mesh/0" or "Material/1". The empty handle when there is no such asset.
Time
Game time. It runs at real time multiplied by the time scale.
Time.Delta (number, read only): Seconds of game time since the last update. The same number OnUpdate is given.Time.Now (number, read only): Seconds of game time since the scene started.Time.Scale (number): How fast game time runs. 1 is normal speed, 0.5 is half speed, 0 pauses the game. Timers, tweens and fixed updates follow it.
math
Lua's own math table (math.floor, math.sin, math.random, math.pi and the rest), with these added.
math.clamp(value: number, min: number, max: number) -> number: The value, or the nearer limit when it is outside them.math.lerp(a: number, b: number, t: number) -> number: The number a fraction t of the way from a to b.math.sign(value: number) -> number: 1 for a positive number, -1 for a negative one, 0 for zero.math.approach(current: number, target: number, step: number) -> number: Moves current towards target by at most step, and never past it. For a value that should catch up at a steady speed: speed = math.approach(speed, wanted, 10 * deltaTime).
Timer
Runs things later. Timers follow game time, so they stop while the game is paused, and all of them are dropped when the scene stops.
Timer.After(seconds: number, callback: fun()) -> TimerHandle: Calls the function once, after this many seconds.Timer.Every(seconds: number, callback: fun()) -> TimerHandle: Calls the function again and again, this many seconds apart.Timer.Cancel(timer: TimerHandle): Stops a timer made by After or Every.Timer.Start(routine: fun(...: any), ...: any): Runs a function as a coroutine, passing it the extra arguments. Inside it, Timer.Wait pauses the function without stopping the game.Timer.Wait(seconds?: number): Inside a function run by Timer.Start: pauses it for this many seconds. With no argument, until the next update.
Tween
Moves a value to a target over time, a little each update: an entity's Position, Rotation or Scale, a light's Color or Intensity, or any other number or Vec3 that can be read and set. Tweens follow game time and are dropped when the scene stops. One whose entity is destroyed ends quietly.
Tween.To(target: any, property: string, value: number|Vec3, seconds: number, easing?: "Linear"|"EaseIn"|"EaseOut"|"EaseInOut", onDone?: fun()) -> TweenHandle: Takes target[property] from what it is now to value over this many seconds. target is an entity or a component and property is its name as text: Tween.To(self.Entity, "Position", Vec3(0, 3, 0), 2). easing is "Linear", "EaseIn", "EaseOut" or "EaseInOut" (the default, when left out). onDone, when given, is called once it arrives.Tween.Cancel(tween: TweenHandle): Stops a tween where it is. onDone is not called.
SaveData
Saved games, kept in the player's own folder for this game and still there the next time it runs. A save is a table: numbers, booleans, text, Vec3 values and tables of those, as deep as needed. Entities and functions cannot be saved, so save what is needed to make them again. A save's name is letters, digits, spaces, dashes and underscores.
SaveData.Save(name: string, data: table) -> boolean: Writes a table as the save with that name, replacing one that was there. False when the file could not be written. A value that cannot be saved is an error that names it.SaveData.Load(name: string) -> table?: Reads a save back as the table that was saved. nil when there is no save with that name or it cannot be read.SaveData.Exists(name: string) -> boolean: Whether there is a save with that name.SaveData.Delete(name: string) -> boolean: Deletes a save. False when there was none.SaveData.List() -> string[]: The names of every save, in alphabetical order. For a "load game" screen.
Settings
What the player chose, kept between runs: the volumes set with Audio.SetVolume, the keys set with Input.SetBindings, and the window's size. The game starts with the project's own settings, and with the player's laid over them once Settings.Save has been called.
Settings.Save() -> boolean: Keeps the volumes, key bindings and window size as they are now, for the next run. Call it when the player leaves the settings screen.Settings.Reset(): Goes back to the project's own volumes and key bindings, and forgets what the player chose.Settings.SetResolution(width: integer, height: integer, fullscreen?: boolean): Changes the window's size, or with fullscreen true takes the whole screen at the screen's own resolution. Has no effect on the editor's window.Settings.GetResolution() -> integer, integer, boolean: The window's size and whether it is fullscreen.
UICanvas
Component: the top of a piece of screen UI. The UIElements under it in the hierarchy are laid out over the whole view and drawn on top of the scene. Sizes are in the canvas's reference units and scale evenly to fit the real view.
Visible (boolean): Off, the whole canvas is hidden and cannot be clicked. How a pause menu is shown and hidden.canvas:GetReferenceSize() -> number, number: The screen size the UI was designed for.canvas:SetReferenceSize(width: number, height: number): Sets the screen size the UI is designed for.
UIElement
Component: one piece of screen UI, placed inside the nearest UIElement above it or the canvas. A script on the same entity hears what the player does to it through functions called by name: OnClick, OnValueChanged, OnHoverEnter and OnHoverExit. The arrow keys and a gamepad's D-pad move between buttons, and Enter, Space or the gamepad's A press one.
Type (string): "Panel", "Image", "Text", "Button", "Slider", "Toggle" or "ProgressBar".Visible (boolean): Off, it and everything under it is hidden and cannot be clicked.Text (string): The words of a Text, or the label of a Button or a Toggle.FontSize (number): The height of the letters, in the canvas's reference units.Font (AssetHandle): A .ttf file. Unset, the built-in font.Texture (AssetHandle): The picture of an Image, or behind a Panel or a Button.Interactable (boolean): A Button, Slider or Toggle that is not interactable is faded and ignores the player.Value (number): A Slider's or ProgressBar's value, from 0 to 1.Checked (boolean): Whether a Toggle is ticked.Align (string): How a Text's words sit in its rectangle: "Left", "Center" or "Right".Color (Vec3): The rectangle's colour, or for a Text the colour of its letters.Alpha (number): How solid it is, from 0 (see-through) to 1.TextColor (Vec3): The colour of a Button's or Toggle's label and of a Slider's handle.element:GetPosition() -> number, number: How far it is moved from where it is fastened, in reference units. Y is down.element:SetPosition(x: number, y: number): How far it is moved from where it is fastened, in reference units. Y is down.element:GetSize() -> number, number: Its size, in reference units.element:SetSize(width: number, height: number): Its size, in reference units.X (number): How far right it is moved from where it is fastened, in reference units. bar.X = 40.Y (number): How far down it is moved from where it is fastened, in reference units.Width (number): Its width, in reference units. For a bar that grows: bar.Width = 300 * health.Height (number): Its height, in reference units.element:GetAnchor() -> number, number: Where in its parent it is fastened, from (0, 0) at the top left to (1, 1) at the bottom right.element:SetAnchor(x: number, y: number): Where in its parent it is fastened, from (0, 0) at the top left to (1, 1) at the bottom right.element:GetPivot() -> number, number: Which point of itself is fastened there, counted the same way.element:SetPivot(x: number, y: number): Which point of itself is fastened there, counted the same way.element:GetStretch() -> number, number: The share of its parent's size that is added to its own. (1, 1) with a size of zero fills the parent.element:SetStretch(x: number, y: number): The share of its parent's size that is added to its own. (1, 1) with a size of zero fills the parent.element:Focus(): Gives it the focus, so the keyboard or a gamepad starts from it. What a menu does to its first button when it opens.
Text
Component: words in the world, on a flat sheet that stands where the entity is. For signs, labels and names over heads.
Text (string): The words. A line break starts a new line.Size (number): The height of the letters, in world units.Font (AssetHandle): A .ttf file. Unset, the built-in font.FaceCamera (boolean): Turns to face the camera wherever it is.Align (string): Which side of the entity the words start from: "Left", "Center" or "Right".Color (Vec3): The colour of the letters.
SkinnedMeshRenderer
Component: draws a mesh that a skeleton bends. With an Animator on the same entity it moves.
Mesh (AssetHandle): The mesh to draw: a part of a model that has a skeleton.Skeleton (AssetHandle): The skeleton the mesh is tied to: a part of the same model.renderer:GetMaterial(slot: integer) -> AssetHandle: The material in a slot, counting from 1.renderer:SetMaterial(slot: integer, material: AssetHandle): Puts a material in a slot, counting from 1.
Animator
Component: moves the entity's skinned mesh, through the states of an animator controller or by playing one clip on a loop. A script steers it by setting the controller's parameters, which its transitions test. A state's events call functions on the entity's scripts by name.
Controller (AssetHandle): A .cairnanimator file: states, transitions and parameters. Changing it starts the animator over.Clip (AssetHandle): With no controller, the clip to play on a loop: an animation of a model.Speed (number): Multiplies how fast everything plays.Playing (boolean): Off, it holds the pose it is in.animator:Set(name: string, value: number|boolean): Sets one of the controller's parameters, to a number or to true or false. An error when the controller has no parameter with that name.animator:Get(name: string) -> number: A parameter's value. true is 1 and false is 0.animator:Play(state: string, fade?: number): Goes to a state now, whatever the transitions say, fading from the present pose over this many seconds (none when left out). An error when there is no such state.animator:GetState() -> string: The name of the state it is in. An animator that plays a clip with no controller is in "Clip".animator:IsFinished() -> boolean: True once a state that does not loop has played to its end.
ParticleSystem
Component: emits small squares that face the camera, move, fade and die: smoke, sparks, dust. Changes take effect at once on what is emitted from then on.
Playing (boolean): Off, nothing new is emitted. What is in the air lives on.Looping (boolean): Round and round. Off, it emits for Duration seconds and stops.Duration (number): The length of a round, in seconds.Rate (number): Particles per second, as a steady stream.MaxParticles (integer): Emission stops at this many alive.LifetimeMin (number): The shortest a particle lives, in seconds.LifetimeMax (number): The longest a particle lives, in seconds.SpeedMin (number): The slowest a particle leaves.SpeedMax (number): The fastest a particle leaves.Direction (Vec3): Which way particles leave, relative to the entity.Spread (number): How many degrees off Direction a particle may leave. 180 is every way.Radius (number): Particles start within this distance of the entity.Gravity (number): How much gravity pulls on them. 1 is the world's, 0 none, negative makes them rise.StartSize (number): The side of a particle's square when it is born, in world units.EndSize (number): The side of a particle's square when it dies.Texture (AssetHandle): The picture on each particle. Unset, a soft round dot.StartColor (Vec3): A particle's colour when it is born. Above 1 it glows.StartAlpha (number): How solid a particle is when it is born, from 0 to 1.EndColor (Vec3): A particle's colour when it dies.EndAlpha (number): How solid a particle is when it dies. 0 fades it away.Blend (string): "Additive" adds light, for fire and sparks. "Alpha" covers what is behind, for smoke and dust.particles:Burst(count: integer): Emits this many particles at once, now, on top of whatever else the system does. For a hit, a pickup, a landing.particles:GetCount() -> integer: How many particles are in the air.
AudioSource
Component: plays a sound from where the entity is. Changes to Volume and Pitch are heard at once. The others take effect the next time it plays.
Clip (AssetHandle): The sound file: .wav, .mp3 or .flac. Get one with Assets.Find.Bus (string): "Sfx" or "Music": which volume control it is under.Volume (number): From 0 (silent) up. 1 is as recorded.Pitch (number): 1 is as recorded, 2 an octave up and twice as fast.Loop (boolean): Starts again when it ends.PlayOnStart (boolean): Starts when the scene does.Spatial (boolean): Heard from the entity's position, louder when the listener is near. Off, it sounds the same everywhere.MinDistance (number): Within this distance it is at full volume.MaxDistance (number): Beyond this distance it is silent.Stream (boolean): Read from the file as it plays and never held in memory whole. For music.LoopStart (number): Where a looping sound goes back to, in seconds, so music can play its opening once.LoopEnd (number): Where a looping sound turns back, in seconds. 0 is the end of the file.source:Play() -> boolean: Plays the sound from its beginning. False when the clip cannot be played.source:Stop(): Stops the sound.source:IsPlaying() -> boolean: Whether the sound is playing. False once it has played to its end.
AudioListener
Component: where spatial sounds are heard from. Without one in the scene it is the primary camera.
Active (boolean): With several listeners in a scene, the first active one is used.
Audio
Volumes and effects for everything that plays, and sounds that need no entity. A bus is "Master", "Music" or "Sfx": every sound plays on Music or Sfx, and both go through Master.
Audio.GetVolume(bus: "Master"|"Music"|"Sfx") -> number: A bus's volume, from 0 to 1.Audio.SetVolume(bus: "Master"|"Music"|"Sfx", volume: number): Sets a bus's volume. What a volume slider in a settings screen calls.Audio.SetLowPass(bus: "Master"|"Music"|"Sfx", cutoff: number): Muffles a bus: frequencies above the cutoff, in hertz, are taken out. 500 sounds like being under water. 0 turns it off. On Master it reaches both other buses.Audio.SetReverb(bus: "Master"|"Music"|"Sfx", amount: number): Adds the echo of a room to a bus, from 0 (none) to 1 (a cathedral).Audio.SetMuted(bus: "Master"|"Music"|"Sfx", muted: boolean): Silences a bus, or lets it play again at the volume it had. What a mute button calls.Audio.IsMuted(bus: "Master"|"Music"|"Sfx") -> boolean: Whether a bus is muted.Audio.PlayOneShot(clip: AssetHandle, volume?: number, position?: Vec3) -> boolean: Plays a sound once on the Sfx bus, with no entity needed. volume is 1 when left out. With a position it is heard from there. Without one it sounds the same everywhere.
Input
What the player is pressing. Ask about actions by the names the project's input map gives them ("Jump", "MoveX"), so the keys can be changed without touching scripts. Keys and buttons are named as text: "Space", "W", "Left", "Mouse Left", "Gamepad A", "Gamepad LeftX". A minus in front ("-A") binds one the other way, which is how two keys make an axis.
Input.GetValue(action: string) -> number: The action's value: 1 while a binding is held, -1 for one bound the other way, 0 for both or neither, and anything between from a stick. An action that is not in the map is 0.Input.IsDown(action: string) -> boolean: Whether the action is held.Input.WasPressed(action: string) -> boolean: True in the one frame the action went down. Ask in OnUpdate: a fixed update can run twice in a frame, or not at all.Input.WasReleased(action: string) -> boolean: True in the one frame the action was let go.Input.IsKeyDown(name: string) -> boolean: Whether one key or button is held, whatever the input map says.Input.WasKeyPressed(name: string) -> boolean: True in the one frame that key or button went down.Input.GetLastPressed() -> string?: The key or button that went down in this frame, or nil. What a "press a key" screen for changing bindings waits for.Input.GetMousePosition() -> number, number: Where the mouse is, in window pixels from the top left.Input.GetViewPosition() -> number, number: Where the mouse is in the game's picture, from (0, 0) at the top left to (1, 1) at the bottom right. The same in the editor's viewport as in the game's own window, which GetMousePosition is not. For aiming at where the mouse points.Input.GetViewSize() -> number, number: The size of the game's picture in pixels. Zero before the first frame is drawn.Input.GetMouseDelta() -> number, number: How far the mouse moved in this frame. Reported while the cursor is locked too, which is what a camera that looks around uses.Input.GetScroll() -> number: How far the wheel turned in this frame. Up is positive.Input.SetCursorLocked(locked: boolean): Hides the cursor and holds it in the window, while GetMouseDelta keeps reporting. Unlocked again when the game stops.Input.IsCursorLocked() -> boolean: Whether the cursor is locked.Input.SetCursorVisible(visible: boolean): Shows or hides the cursor without holding it in place.Input.GetBindings(action: string) -> string[]: The keys, buttons and sticks bound to an action. Empty for an action that is not in the map.Input.SetBindings(action: string, names: string[]): Binds an action to a new list of keys, buttons and sticks, adding the action when it is new. An empty list removes it. Lasts until the game stops.
DefineScript
For TypeScript scripts, which end with export = DefineScript({ ... }). It tells TypeScript what this is in the script's functions. A Lua script does not need it.
DefineScript(script: table) -> table: Gives the script's table back as it is. It changes nothing when the game runs.
require
Shares code between scripts. Put functions in a Lua file that returns a table, and other scripts get that table with local Utils = require("Assets/Scripts/Utils"). The path is from the project's folder, with or without .lua, and dots work in place of slashes. A file is run once and every script gets the same table. It reaches the project's own scripts only.
require(path: string) -> any: What the Lua file at that path in the project returns. An error when there is no such script, when it does not load, or when two files require each other.
Events
Lets scripts tell each other that something happened without knowing who is listening. One script says Events.Emit("CoinCollected", 5), and every script that asked with Events.On("CoinCollected", ...) is called. All listeners are dropped when the scene stops.
Events.On(name: string, callback: fun(...: any), owner?: Entity) -> EventListener: Calls the function whenever the event with this name is emitted, with whatever was emitted. owner is optional and is usually self.Entity: the listener is dropped when that entity is destroyed, and is not called while it is switched off. Without an owner it listens until the scene stops or Events.Off.Events.Off(listener: EventListener): Stops a listener that Events.On returned.Events.Emit(name: string, ...: any) -> integer: Tells every listener of this event, passing the extra arguments. Returns how many were told. An error in one listener is logged and does not stop the others.
Color
Colours, as the Vec3 every colour property takes: red, green and blue from 0 to 1, in linear light. Above 1 is brighter than white, which makes lights stronger and emissive things glow.
Color.RGB(red: number, green: number, blue: number) -> Vec3: A colour from the 0 to 255 numbers a paint program shows, turned into linear light. Color.RGB(255, 128, 0) is orange.Color.Hex(text: string) -> Vec3: A colour from the six letters and digits the web uses, with or without the #: Color.Hex("#ff8000"). Turned into linear light.Color.White (Vec3, read only): (1, 1, 1).Color.Black (Vec3, read only): (0, 0, 0).Color.Gray (Vec3, read only): (0.5, 0.5, 0.5).Color.Red (Vec3, read only): (1, 0, 0).Color.Green (Vec3, read only): (0, 1, 0).Color.Blue (Vec3, read only): (0, 0, 1).Color.Yellow (Vec3, read only): (1, 1, 0).Color.Cyan (Vec3, read only): (0, 1, 1).Color.Magenta (Vec3, read only): (1, 0, 1).Color.Orange (Vec3, read only): (1, 0.5, 0).
Debug
Draws lines in the editor's viewport while the game plays, for seeing what a script is doing: where a ray goes, how far something reaches. Each is drawn for one frame, so call it every update for as long as it should show. In an exported game these do nothing. color is optional: a Vec3, white when left out.
Debug.Line(from: Vec3, to: Vec3, color?: Vec3): A line between two points of the world.Debug.Ray(origin: Vec3, direction: Vec3, color?: Vec3): A line from a point along a direction, as long as the direction is. For showing a Physics.Raycast: Debug.Ray(origin, direction * maxDistance).Debug.Sphere(center: Vec3, radius: number, color?: Vec3): Three circles round a point: a ball's outline.Debug.Box(center: Vec3, halfExtents: Vec3, color?: Vec3): The edges of a box that is not turned. halfExtents is half its size on each axis.
Field
Kinds of field for a script's Fields table, beyond plain numbers, booleans, text and Vec3: ones that point at another entity or at an asset, which are then set in the inspector by picking or dragging, and numbers with limits. Each takes an optional last argument, a table with Tip: text the editor shows for the field. Fields = { Speed = Field.Number(5, { Min = 0, Max = 20 }), Target = Field.Entity(), Bullet = Field.Prefab({ Tip = "What is fired" }) }.
Field.Number(defaultValue: number, options?: FieldOptions) -> FieldDescription<number>: A number, which in a script is read as a plain number. options may giveMinandMax, and the inspector then shows a slider between them.Field.Entity(options?: FieldOptions) -> FieldDescription<Entity?>: Another entity of the scene. In a script it is that entity, or nil when none was set. A copy of a group of entities keeps its references among the copies.Field.Prefab(options?: FieldOptions) -> FieldDescription<AssetHandle>: A prefab, for Scene.Instantiate. In a script it is an AssetHandle: the empty one when none was set.Field.Material(options?: FieldOptions) -> FieldDescription<AssetHandle>: A material, for a renderer's SetMaterial.Field.Texture(options?: FieldOptions) -> FieldDescription<AssetHandle>: A picture.Field.Audio(options?: FieldOptions) -> FieldDescription<AssetHandle>: A sound, for Audio.PlayOneShot or an AudioSource's Clip.Field.Scene(options?: FieldOptions) -> FieldDescription<AssetHandle>: A scene, for Scene.Load.Field.Mesh(options?: FieldOptions) -> FieldDescription<AssetHandle>: A mesh: a part of a model.Field.Font(options?: FieldOptions) -> FieldDescription<AssetHandle>: A font, for a Text or a UIElement.Field.Animator(options?: FieldOptions) -> FieldDescription<AssetHandle>: An animator controller.
Log
Writes to the log, which the editor shows in its console. print is the same as Log.Info.
Log.Info(...: any): Logs the arguments, separated by spaces.Log.Warn(...: any): Logs a warning.Log.Error(...: any): Logs an error.