Esta página aún no está traducida: se muestra en inglés.
Scripting API
Generated from EngineApi.cs, the file every script is compiled against. Scripts derive from Behaviour. Every member has an example: the line beside it, and the whole script under each table, which compiles as it stands (drop it into Scripts/).
105 types, 833 of 833 entries have a description.
Contents
- Vector3
- Vector2
- Color
- Quaternion
- Mathf
- Keyframe
- AnimationCurve
- Time
- Audio
- Scene
- SceneLoad
- ContentPacks
- ContentPack
- Application
- CursorLockMode
- Cursor
- Screen
- SaveGame
- SaveData
- PlayerPrefs
- NeuxDebug
- Localization
- Debug
- UIElement
- UIEvent
- UIButton
- UIText
- UIImage
- UISlider
- UIToggle
- UIInput
- Random
- UI
- Camera
- Input
- AssetRef
- AudioClip
- Texture
- Texture2D
- Sprite
- Material
- Mesh
- Prefab
- AnimationClip
- TextAsset
- Gizmos
- Timeline
- HeaderAttribute
- TooltipAttribute
- SpaceAttribute
- RangeAttribute
- HideInInspectorAttribute
- MinAttribute
- TextAreaAttribute
- MultilineAttribute
- MenuItemAttribute
- ContextMenuAttribute
- Selection
- AssetDatabase
- Undo
- Handles
- CustomEditorAttribute
- Editor
- EditorWindow
- MessageType
- GUILayout
- EditorGUILayout
- DataAsset
- DataTable
- Transform
- GameObject
- WaitForSeconds
- WaitForSecondsRealtime
- WaitUntil
- WaitWhile
- WaitForEndOfFrame
- Coroutine
- LayerMask
- Ray
- Plane
- Bounds
- Matrix4x4
- Behaviour
- XR
- XRHand
- RaycastHit
- Physics
- Rigidbody
- Animator
- CharacterController
- NavAgent
- Component
- AudioSource
- Light
- MeshRenderer
- Collider
- Events
- Inventory
- Tween
- ModelAnimation
- Subtitles
- Achievements
- BtStatus
- BtNode
- BT
Vector3
struct Vector3
A 3D vector of floats: positions, directions, scales and Euler angles in degrees.
| Member | Description | Example |
|---|---|---|
float x, y, z | The components. | Debug.Log("spawn at x " + spawn.x + ", y " + spawn.y + ", z " + spawn.z); |
Vector3(float x, float y, float z) | Builds a vector from its components. | Vector3 spawn = new Vector3(2f, 0.5f, -4f); |
static Vector3 zero | (0, 0, 0). | transform.position = Vector3.zero + spawn; |
static Vector3 one | (1, 1, 1). | transform.scale = Vector3.one * 2f; |
static Vector3 up | (0, 1, 0). | Vector3 jump = Vector3.up * 5f; |
static Vector3 down | (0, -1, 0). | Vector3 fall = Vector3.down * 9.8f; |
static Vector3 right | (1, 0, 0). | Vector3 strafe = Vector3.right - Vector3.left; |
static Vector3 left | (-1, 0, 0). | Vector3 strafe = Vector3.right - Vector3.left; |
static Vector3 forward | The world's forward is -Z (the editor camera looks down -Z). | Vector3 ahead = Vector3.forward; |
static Vector3 back | (0, 0, 1). | Vector3 behind = Vector3.back; |
float Length | The length of the vector. | Debug.Log("length " + offset.Length + " = " + offset.magnitude); |
float SqrLength | The squared length; cheaper than Length for comparisons. | Debug.Log("squared " + offset.SqrLength + " = " + offset.sqrMagnitude); |
float magnitude | Same as Length (the other common spelling). | Debug.Log("length " + offset.Length + " = " + offset.magnitude); |
float sqrMagnitude | Same as SqrLength (the other common spelling). | Debug.Log("squared " + offset.SqrLength + " = " + offset.sqrMagnitude); |
Vector3 normalized | Same as Normalized (the other common spelling). | Debug.Log("direction " + dir + " = " + offset.normalized); |
Vector3 Normalized | The same direction with length 1 (zero stays zero). | Vector3 dir = offset.Normalized; |
static Vector3 operator +(Vector3 a, Vector3 b) | Component-wise sum. | Vector3 sum = offset + Vector3.up; |
static Vector3 operator -(Vector3 a, Vector3 b) | Component-wise difference. | Vector3 toTarget = target.transform.position - transform.position; |
static Vector3 operator -(Vector3 a) | The opposite vector. | Vector3 opposite = -offset; |
static Vector3 operator *(Vector3 a, float s) | Scales by a number. | Vector3 twice = offset * 2f; |
static Vector3 operator *(float s, Vector3 a) | Scales by a number. | Vector3 alsoTwice = 2f * offset; |
static Vector3 operator /(Vector3 a, float s) | Divides by a number. | Vector3 half = offset / 2f; |
static bool operator ==(Vector3 a, Vector3 b) | True when all components are exactly equal. | if (transform.position == Vector3.zero) Debug.Log("at the origin"); |
static bool operator !=(Vector3 a, Vector3 b) | True when any component differs. | if (velocity != Vector3.zero) transform.LookAt(transform.position + velocity); |
override bool Equals(object o) | Same as ==. | if (twice == alsoTwice && twice != half && twice.Equals(alsoTwice)) |
override int GetHashCode() | A hash of the components. | Debug.Log("same vector, hash " + twice.GetHashCode()); |
static float Dot(Vector3 a, Vector3 b) | The dot product. | float facing = Vector3.Dot(Vector3.forward, dir); |
static Vector3 Cross(Vector3 a, Vector3 b) | The cross product. | Vector3 normal = Vector3.Cross(Vector3.right, Vector3.forward); |
static float Distance(Vector3 a, Vector3 b) | The distance between two points. | if (Vector3.Distance(transform.position, goal) > 5f) |
static Vector3 Lerp(Vector3 a, Vector3 b, float t) | Interpolates from a to b; t is clamped to 0..1. | transform.position = Vector3.Lerp(transform.position, goal, 2f * deltaTime); |
static Vector3 MoveTowards(Vector3 from, Vector3 to, float maxDelta) | Moves from one point towards another by at most maxDelta. | transform.position = Vector3.MoveTowards(transform.position, goal, speed * deltaTime); |
override string ToString() | The vector as text. | Debug.Log(offset.ToString()); |
Example (Vector3.cs)
// Vector3: positions, directions and distances in 3D.
public class Vector3Example : Behaviour
{
public GameObject target;
public float speed = 3f;
public override void Start()
{
// The constructor and the x, y, z components.
Vector3 spawn = new Vector3(2f, 0.5f, -4f);
spawn.y += 1f;
Debug.Log("spawn at x " + spawn.x + ", y " + spawn.y + ", z " + spawn.z);
// zero, one: the origin, and a scale of 1 on every axis.
transform.position = Vector3.zero + spawn;
transform.scale = Vector3.one * 2f;
// up, down, right, left, forward, back: the six unit directions (forward is -Z).
Vector3 jump = Vector3.up * 5f;
Vector3 fall = Vector3.down * 9.8f;
Vector3 strafe = Vector3.right - Vector3.left; // (2, 0, 0)
Vector3 ahead = Vector3.forward; // (0, 0, -1)
Vector3 behind = Vector3.back; // (0, 0, 1)
Debug.Log(jump + " " + fall + " " + strafe + " " + ahead + " " + behind);
// Length and SqrLength (magnitude and sqrMagnitude are the same, the other common spelling).
Vector3 offset = new Vector3(3f, 0f, 4f);
Debug.Log("length " + offset.Length + " = " + offset.magnitude); // 5
Debug.Log("squared " + offset.SqrLength + " = " + offset.sqrMagnitude); // 25
// Normalized (normalized): the same direction with length 1.
Vector3 dir = offset.Normalized;
Debug.Log("direction " + dir + " = " + offset.normalized);
// The operators: add, subtract, negate, scale and divide.
Vector3 sum = offset + Vector3.up;
Vector3 diff = offset - Vector3.up;
Vector3 opposite = -offset;
Vector3 twice = offset * 2f;
Vector3 alsoTwice = 2f * offset;
Vector3 half = offset / 2f;
Debug.Log(sum + " " + diff + " " + opposite + " " + twice + " " + alsoTwice + " " + half);
// == and != compare every component exactly; Equals is the same as ==; GetHashCode lets a vector be a dictionary key.
if (twice == alsoTwice && twice != half && twice.Equals(alsoTwice))
Debug.Log("same vector, hash " + twice.GetHashCode());
// Dot: 1 when two unit vectors point the same way, 0 at right angles, -1 when opposite.
float facing = Vector3.Dot(Vector3.forward, dir);
// Cross: a vector at right angles to both (the normal of the plane they lie in).
Vector3 normal = Vector3.Cross(Vector3.right, Vector3.forward);
Debug.Log("facing " + facing + ", normal " + normal);
// ToString: the vector as text, for the Console.
Debug.Log(offset.ToString());
}
public override void Update(float deltaTime)
{
if (target == null) return;
Vector3 goal = target.transform.position;
// Distance: how far apart two points are.
if (Vector3.Distance(transform.position, goal) > 5f)
// MoveTowards: a step of at most speed * time towards the goal, never past it.
transform.position = Vector3.MoveTowards(transform.position, goal, speed * deltaTime);
else
// Lerp: a point between two others; 0 is the first, 1 the second (here: ease in over the last stretch).
transform.position = Vector3.Lerp(transform.position, goal, 2f * deltaTime);
}
}
Vector2
struct Vector2
A 2D vector of floats: screen points, 2D positions, stick input. Converts to and from Vector3 (z = 0).
| Member | Description | Example |
|---|---|---|
float x, y | The components. | p.x += 1f; |
Vector2(float x, float y) | Builds a vector from its components. | Vector2 p = new Vector2(3f, 4f); |
static Vector2 zero | (0, 0). | Vector2 origin = Vector2.zero; |
static Vector2 one | (1, 1). | Vector2 size = Vector2.one * 2f; |
static Vector2 up | (0, 1). | Vector2 jump = Vector2.up * 6f; |
static Vector2 down | (0, -1). | Vector2 fall = Vector2.down; |
static Vector2 right | (1, 0). | Vector2 east = Vector2.right; |
static Vector2 left | (-1, 0). | Vector2 west = Vector2.left; |
float magnitude | The length. | Debug.Log("length " + v.magnitude + ", squared " + v.sqrMagnitude + ", direction " + v.normalized); |
float sqrMagnitude | The squared length. | Debug.Log("length " + v.magnitude + ", squared " + v.sqrMagnitude + ", direction " + v.normalized); |
Vector2 normalized | The same direction with length 1 (zero stays zero). | Debug.Log("length " + v.magnitude + ", squared " + v.sqrMagnitude + ", direction " + v.normalized); |
static Vector2 operator +(Vector2 a, Vector2 b) | The sum. | Vector2 goal = here + input * speed; |
static Vector2 operator -(Vector2 a, Vector2 b) | The difference. | Vector2 diff = v - east; |
static Vector2 operator -(Vector2 a) | The opposite vector. | Vector2 back = -v; |
static Vector2 operator *(Vector2 a, float s) | Scales by a number. | Vector2 twice = v * 2f; |
static Vector2 operator *(float s, Vector2 a) | Scales by a number. | Vector2 alsoTwice = 2f * v; |
static Vector2 operator /(Vector2 a, float s) | Divides by a number. | Vector2 half = v / 2f; |
static bool operator ==(Vector2 a, Vector2 b) | True when both components are exactly equal. | if (input == Vector2.zero) velocity = Vector2.zero; |
static bool operator !=(Vector2 a, Vector2 b) | True when either component differs. | if (twice != half) Debug.Log("different"); |
override bool Equals(object o) | Same as ==. | if (twice == alsoTwice && twice != half && twice.Equals(alsoTwice)) |
override int GetHashCode() | A hash of the components. | Debug.Log("same, hash " + twice.GetHashCode()); |
static implicit operator Vector3(Vector2 v) | A 2D vector as a 3D one (z = 0). | Vector3 inWorld = v; |
static implicit operator Vector2(Vector3 v) | A 3D vector's x and y. | Vector2 flat = transform.position; |
static float Dot(Vector2 a, Vector2 b) | The dot product. | Debug.Log("dot " + Vector2.Dot(east, v.normalized) + ", angle " + Vector2.Angle(east, v)); |
static float Distance(Vector2 a, Vector2 b) | The distance between two points. | if (Vector2.Distance(here, goal) > 0.01f) |
static Vector2 Lerp(Vector2 a, Vector2 b, float t) | Interpolates from a to b; t is clamped to 0..1. | velocity = Vector2.Lerp(velocity, input * speed, 10f * deltaTime); |
static Vector2 MoveTowards(Vector2 from, Vector2 to, float maxDelta) | Moves from one point towards another by at most maxDelta. | transform.position = Vector2.MoveTowards(here, here + velocity, speed * deltaTime); |
static float Angle(Vector2 a, Vector2 b) | The angle in degrees between two directions. | Debug.Log("dot " + Vector2.Dot(east, v.normalized) + ", angle " + Vector2.Angle(east, v)); |
override string ToString() | The vector as text. | Debug.Log(v.ToString()); |
Example (Vector2.cs)
// Vector2: positions and directions in 2D games and on the screen.
public class Vector2Example : Behaviour
{
public float speed = 4f;
Vector2 velocity;
public override void Start()
{
// The constructor and the x, y components.
Vector2 p = new Vector2(3f, 4f);
p.x += 1f;
Debug.Log("x " + p.x + ", y " + p.y);
// zero, one and the four unit directions.
Vector2 origin = Vector2.zero;
Vector2 size = Vector2.one * 2f;
Vector2 jump = Vector2.up * 6f;
Vector2 fall = Vector2.down;
Vector2 east = Vector2.right;
Vector2 west = Vector2.left;
Debug.Log(origin + " " + size + " " + jump + " " + fall + " " + east + " " + west);
// magnitude, sqrMagnitude and normalized: length, squared length, and the direction with length 1.
Vector2 v = new Vector2(3f, 4f);
Debug.Log("length " + v.magnitude + ", squared " + v.sqrMagnitude + ", direction " + v.normalized);
// The operators: add, subtract, negate, scale and divide.
Vector2 sum = v + east;
Vector2 diff = v - east;
Vector2 back = -v;
Vector2 twice = v * 2f;
Vector2 alsoTwice = 2f * v;
Vector2 half = v / 2f;
Debug.Log(sum + " " + diff + " " + back + " " + twice + " " + alsoTwice + " " + half);
// == and != compare both components exactly; Equals is the same as ==; GetHashCode for dictionary keys.
if (twice == alsoTwice && twice != half && twice.Equals(alsoTwice))
Debug.Log("same, hash " + twice.GetHashCode());
// A Vector2 turns into a Vector3 (z = 0) by itself, and a Vector3 into a Vector2 (its x and y).
Vector3 inWorld = v;
Vector2 flat = transform.position;
Debug.Log(inWorld + " " + flat);
// Dot: how alike two directions are. Angle: the degrees between them.
Debug.Log("dot " + Vector2.Dot(east, v.normalized) + ", angle " + Vector2.Angle(east, v));
// ToString: the vector as text.
Debug.Log(v.ToString());
}
public override void Update(float deltaTime)
{
// A 2D character: read the arrows, move at a steady speed.
Vector2 input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
Vector2 here = transform.position;
Vector2 goal = here + input * speed;
// Distance: how far apart two points are.
if (Vector2.Distance(here, goal) > 0.01f)
{
// Lerp: blend the velocity towards what the input asks for, so starts and stops are soft.
velocity = Vector2.Lerp(velocity, input * speed, 10f * deltaTime);
// MoveTowards: a step of at most the given length towards the goal.
transform.position = Vector2.MoveTowards(here, here + velocity, speed * deltaTime);
}
}
}
Color
struct Color
A colour: red, green, blue and alpha (opacity), each 0..1.
| Member | Description | Example |
|---|---|---|
float r, g, b, a | The channels. | Debug.Log("red " + glass.r + ", green " + glass.g + ", blue " + glass.b + ", alpha " + glass.a); |
Color(float r, float g, float b, float a = 1f) | A colour from its channels (alpha 1 when left out). | public Color team = new Color(0.2f, 0.6f, 1f); |
static Color white | (1, 1, 1). | Color.white, Color.black, Color.red, Color.green, Color.blue, Color.yellow, |
static Color black | (0, 0, 0). | Color.white, Color.black, Color.red, Color.green, Color.blue, Color.yellow, |
static Color red | (1, 0, 0). | Debug.Log("red " + glass.r + ", green " + glass.g + ", blue " + glass.b + ", alpha " + glass.a); |
static Color green | (0, 1, 0). | Debug.Log("red " + glass.r + ", green " + glass.g + ", blue " + glass.b + ", alpha " + glass.a); |
static Color blue | (0, 0, 1). | Debug.Log("red " + glass.r + ", green " + glass.g + ", blue " + glass.b + ", alpha " + glass.a); |
static Color yellow | (1, 0.92, 0.016), a warm yellow. | Color.white, Color.black, Color.red, Color.green, Color.blue, Color.yellow, |
static Color cyan | (0, 1, 1). | Color.cyan, Color.magenta, Color.gray, Color.grey, Color.clear, |
static Color magenta | (1, 0, 1). | Color.cyan, Color.magenta, Color.gray, Color.grey, Color.clear, |
static Color gray | (0.5, 0.5, 0.5). | Color.cyan, Color.magenta, Color.gray, Color.grey, Color.clear, |
static Color grey | Same as gray. | Color.cyan, Color.magenta, Color.gray, Color.grey, Color.clear, |
static Color clear | Fully transparent black. | Color.cyan, Color.magenta, Color.gray, Color.grey, Color.clear, |
static Color Lerp(Color x, Color y, float t) | Interpolates channel by channel; t is clamped to 0..1. | gameObject.SetColor(Color.Lerp(team, Color.red, hurt)); |
static Color operator *(Color x, Color y) | Channel-wise product. | Color tinted = team * Color.yellow; |
static Color operator *(Color x, float s) | Scales every channel. | Color dim = team * 0.5f; |
static Color operator +(Color x, Color y) | Channel-wise sum. | Color brighter = team + Color.gray; |
override string ToString() | The colour as text. | Debug.Log(team.ToString()); |
Example (Color.cs)
// Color: colours for materials, lights, UI and debug drawing.
public class ColorExample : Behaviour
{
public Color team = new Color(0.2f, 0.6f, 1f); // r, g, b (alpha is 1 when left out)
float hurt;
public override void Start()
{
// The channels r, g, b, a, each 0 to 1.
Color glass = new Color(0.8f, 0.9f, 1f, 0.3f);
Debug.Log("red " + glass.r + ", green " + glass.g + ", blue " + glass.b + ", alpha " + glass.a);
// The named colours.
Color[] palette =
{
Color.white, Color.black, Color.red, Color.green, Color.blue, Color.yellow,
Color.cyan, Color.magenta, Color.gray, Color.grey, Color.clear,
};
Debug.Log(palette.Length + " named colours; clear is " + Color.clear);
// * with a colour tints (channel by channel); * with a number dims or brightens; + adds light.
Color tinted = team * Color.yellow;
Color dim = team * 0.5f;
Color brighter = team + Color.gray;
Debug.Log(tinted + " " + dim + " " + brighter);
// ToString: the colour as text.
Debug.Log(team.ToString());
gameObject.SetColor(team);
}
public override void OnCollisionEnter(GameObject other)
{
hurt = 1f; // flash red when something hits this object
}
public override void Update(float deltaTime)
{
hurt = Mathf.Max(0f, hurt - deltaTime * 3f);
// Lerp: blend from the team colour to red; 0 is the first colour, 1 the second.
gameObject.SetColor(Color.Lerp(team, Color.red, hurt));
}
}
Quaternion
struct Quaternion
A rotation. Objects face -Z when not turned. A rotation converts to and from the Euler angles (degrees) that transform.rotation holds, so transform.rotation = Quaternion.LookRotation(d) and Quaternion q = transform.rotation both work.
| Member | Description | Example |
|---|---|---|
float x, y, z, w | The components (x, y, z: the axis times sin(angle/2); w: cos(angle/2)). | Debug.Log("x " + raw.x + ", y " + raw.y + ", z " + raw.z + ", w " + raw.w); |
Quaternion(float x, float y, float z, float w) | A rotation from its components. | Quaternion raw = new Quaternion(0f, 0.7071f, 0f, 0.7071f); |
static Quaternion identity | No rotation. | Quaternion none = Quaternion.identity; |
static Quaternion Euler(float ex, float ey, float ez) | The rotation by these Euler angles in degrees (the editor's order: Z, then X, then Y). | Quaternion tilt = Quaternion.Euler(30f, 0f, 0f); |
static Quaternion Euler(Vector3 e) | The rotation by these Euler angles in degrees. | Quaternion tilt = Quaternion.Euler(30f, 0f, 0f); |
Vector3 eulerAngles | This rotation as Euler angles in degrees. | Debug.Log("tilt in degrees: " + tilt.eulerAngles); |
static Quaternion AngleAxis(float degrees, Vector3 axis) | A rotation by degrees about axis. | Quaternion quarterTurn = Quaternion.AngleAxis(90f, Vector3.up); |
static Quaternion LookRotation(Vector3 forward, Vector3 up) | The rotation that turns an object (which faces -Z) to face forward, keeping up (the world's up when left out) up. | Quaternion want = Quaternion.LookRotation(toTarget); |
static Quaternion LookRotation(Vector3 forward) | The rotation that turns an object to face forward (world up kept up). | Quaternion want = Quaternion.LookRotation(toTarget); |
static Quaternion FromToRotation(Vector3 from, Vector3 to) | The rotation turning direction from onto direction to. | Quaternion lean = Quaternion.FromToRotation(Vector3.up, new Vector3(0.3f, 1f, 0f)); |
Quaternion normalized | The same rotation with length 1. | raw = raw.normalized; |
static Quaternion Inverse(Quaternion q) | The opposite rotation. | Quaternion back = Quaternion.Inverse(quarterTurn); |
static float Dot(Quaternion a, Quaternion b) | How alike two rotations are (1 or -1: the same). | Debug.Log("dot " + Quaternion.Dot(quarterTurn * back, none) + ", angle " + Quaternion.Angle(none, quarterTu... |
static float Angle(Quaternion a, Quaternion b) | The angle in degrees between two rotations. | Debug.Log("dot " + Quaternion.Dot(quarterTurn * back, none) + ", angle " + Quaternion.Angle(none, quarterTu... |
static Quaternion Slerp(Quaternion a, Quaternion b, float t) | Turns from a towards b along the shortest arc; t is clamped to 0..1. | transform.rotation = Quaternion.Slerp(now, want, 5f * deltaTime); |
static Quaternion Lerp(Quaternion a, Quaternion b, float t) | Blends two rotations (cheaper than Slerp, fine for small steps); t is clamped to 0..1. | transform.rotation = Quaternion.Lerp(now, wantRolled, 5f * deltaTime); |
static Quaternion RotateTowards(Quaternion from, Quaternion to, float maxDegrees) | Turns from towards to by at most maxDegrees. | transform.rotation = Quaternion.RotateTowards(now, want, turnSpeed * deltaTime); |
static Quaternion operator *(Quaternion a, Quaternion b) | The rotation b, then a. | Quaternion both = tilt * quarterTurn; |
static Vector3 operator *(Quaternion q, Vector3 v) | The vector turned by the rotation. | Vector3 turnedForward = quarterTurn * Vector3.forward; |
static implicit operator Vector3(Quaternion q) | The Euler angles (degrees) of the rotation: what transform.rotation holds. | Vector3 asDegrees = lean; |
static implicit operator Quaternion(Vector3 e) | The rotation by these Euler angles (degrees). | Quaternion fromDegrees = new Vector3(0f, 45f, 0f); |
override string ToString() | The rotation as text. | Debug.Log(asDegrees + " " + fromDegrees.ToString()); |
Example (Quaternion.cs)
// Quaternion: rotations: turning to face something, turning smoothly, combining turns.
public class QuaternionExample : Behaviour
{
public GameObject target;
public float turnSpeed = 120f; // degrees a second
public override void Start()
{
// identity: no rotation at all.
Quaternion none = Quaternion.identity;
// Euler: a rotation from degrees about x, y and z (three numbers or one Vector3).
Quaternion tilt = Quaternion.Euler(30f, 0f, 0f);
Quaternion same = Quaternion.Euler(new Vector3(30f, 0f, 0f));
// eulerAngles: the rotation back as degrees.
Debug.Log("tilt in degrees: " + tilt.eulerAngles);
// AngleAxis: a turn of so many degrees about an axis.
Quaternion quarterTurn = Quaternion.AngleAxis(90f, Vector3.up);
// The constructor and the x, y, z, w components (rarely written by hand: w is cos(angle/2)).
Quaternion raw = new Quaternion(0f, 0.7071f, 0f, 0.7071f);
Debug.Log("x " + raw.x + ", y " + raw.y + ", z " + raw.z + ", w " + raw.w);
// normalized: the same rotation with length 1 (after adding or blending by hand).
raw = raw.normalized;
// * with a rotation: one turn after another (quarterTurn first, then tilt).
Quaternion both = tilt * quarterTurn;
// * with a vector: the vector turned by the rotation.
Vector3 turnedForward = quarterTurn * Vector3.forward;
Debug.Log(both + " " + turnedForward);
// Inverse: the opposite turn; a rotation times its inverse is the identity.
Quaternion back = Quaternion.Inverse(quarterTurn);
// Dot: 1 (or -1) when two rotations are the same. Angle: the degrees between them.
Debug.Log("dot " + Quaternion.Dot(quarterTurn * back, none) + ", angle " + Quaternion.Angle(none, quarterTurn));
// FromToRotation: the turn that takes one direction onto another (lay an object along a slope's normal).
Quaternion lean = Quaternion.FromToRotation(Vector3.up, new Vector3(0.3f, 1f, 0f));
// A rotation turns into Euler degrees and back by itself: transform.rotation holds Euler degrees.
Vector3 asDegrees = lean;
Quaternion fromDegrees = new Vector3(0f, 45f, 0f);
transform.rotation = same;
Debug.Log(asDegrees + " " + fromDegrees.ToString()); // ToString: the rotation as text
}
public override void Update(float deltaTime)
{
if (target == null) return;
Vector3 toTarget = target.transform.position - transform.position;
// LookRotation: the rotation that faces a direction (with world up kept up, or an up of your own).
Quaternion want = Quaternion.LookRotation(toTarget);
Quaternion wantRolled = Quaternion.LookRotation(toTarget, Vector3.right);
Quaternion now = transform.rotation;
if (Input.GetKey("Shift"))
// RotateTowards: turn towards a rotation by at most so many degrees (a turret with a top speed).
transform.rotation = Quaternion.RotateTowards(now, want, turnSpeed * deltaTime);
else if (Input.GetKey("Alt"))
// Lerp: a cheap blend, fine for small steps.
transform.rotation = Quaternion.Lerp(now, wantRolled, 5f * deltaTime);
else
// Slerp: turn along the shortest arc; 0 is the first rotation, 1 the second.
transform.rotation = Quaternion.Slerp(now, want, 5f * deltaTime);
}
}
Mathf
static class Mathf
Float maths helpers (angles in radians unless a name says degrees).
| Member | Description | Example |
|---|---|---|
const float PI | Pi. | Debug.Log("a quarter turn is " + quarter + " = " + Mathf.PI / 2f + " radians, or " + quarter * Mathf.Rad2De... |
const float Deg2Rad | Multiply degrees by this to get radians. | float quarter = 90f * Mathf.Deg2Rad; |
const float Rad2Deg | Multiply radians by this to get degrees. | Debug.Log("a quarter turn is " + quarter + " = " + Mathf.PI / 2f + " radians, or " + quarter * Mathf.Rad2De... |
static int RoundToInt(float v) | Rounds to the nearest whole number, as an int. | Debug.Log("health " + Mathf.RoundToInt(health) + ", at least " + Mathf.FloorToInt(health) + ", at most " + ... |
static int FloorToInt(float v) | Rounds down, as an int. | Debug.Log("health " + Mathf.RoundToInt(health) + ", at least " + Mathf.FloorToInt(health) + ", at most " + ... |
static int CeilToInt(float v) | Rounds up, as an int. | Debug.Log("health " + Mathf.RoundToInt(health) + ", at least " + Mathf.FloorToInt(health) + ", at most " + ... |
static float Sin(float v) | Sine of an angle in radians. | transform.position = new Vector3(Mathf.Cos(angle) * 2f, 1f, Mathf.Sin(angle) * 2f); |
static float Cos(float v) | Cosine of an angle in radians. | transform.position = new Vector3(Mathf.Cos(angle) * 2f, 1f, Mathf.Sin(angle) * 2f); |
static float Exp(float v) | e raised to v (smoothing: 1 - Mathf.Exp(-speed * dt) is how far to move this frame). | float follow = 1f - Mathf.Exp(-6f * deltaTime); |
static float Tan(float v) | Tangent of an angle in radians. | Debug.Log("tan 45 = " + Mathf.Tan(45f * Mathf.Deg2Rad)); |
static float Atan2(float y, float x) | The angle of the point (x, y) in radians. | float facing = Mathf.Atan2(1f, 1f) * Mathf.Rad2Deg; |
static float Sqrt(float v) | Square root. | Debug.Log(Mathf.Sqrt(3f * 3f + 4f * 4f)); |
static float Abs(float v) | Absolute value. | Debug.Log("moving at " + Mathf.Abs(speed) + " to the " + (Mathf.Sign(speed) < 0f ? "left" : "right")); |
static float Sign(float v) | -1, 0 or 1. | Debug.Log("moving at " + Mathf.Abs(speed) + " to the " + (Mathf.Sign(speed) < 0f ? "left" : "right")); |
static float Floor(float v) | Rounds down. | Debug.Log(Mathf.Round(health) + " " + Mathf.Floor(health) + " " + Mathf.Ceil(health)); |
static float Ceil(float v) | Rounds up. | Debug.Log(Mathf.Round(health) + " " + Mathf.Floor(health) + " " + Mathf.Ceil(health)); |
static float Round(float v) | Rounds to the nearest whole number. | Debug.Log(Mathf.Round(health) + " " + Mathf.Floor(health) + " " + Mathf.Ceil(health)); |
static float Min(float a, float b) | The smaller of two numbers. | float heal = Mathf.Min(25f, 100f - health); |
static float Max(float a, float b) | The larger of two numbers. | float damage = Mathf.Max(0f, 30f - 12f); |
static float Clamp(float v, float lo, float hi) | Limits a value to lo..hi. | health = Mathf.Clamp(health - damage + heal, 0f, 100f); |
static float Clamp01(float v) | Limits a value to 0..1. | float bar = Mathf.Clamp01(health / 100f); |
static float Lerp(float a, float b, float t) | Interpolates from a to b; t is clamped to 0..1 (0 gives a, 1 gives b). | float y = Mathf.Lerp(transform.position.y, 1f + lift, follow); |
static float PingPong(float t, float length) | Bounces a value between 0 and length. | float lift = Mathf.PingPong(Time.time, 3f); |
Example (Mathf.cs)
// Mathf: the everyday maths: rounding, clamping, angles, blending.
public class MathfExample : Behaviour
{
public float health = 73.6f;
float angle;
public override void Start()
{
// RoundToInt, FloorToInt, CeilToInt: to a whole number, as an int (for showing on the HUD).
Debug.Log("health " + Mathf.RoundToInt(health) + ", at least " + Mathf.FloorToInt(health) + ", at most " + Mathf.CeilToInt(health));
// Round, Floor, Ceil: the same, staying a float.
Debug.Log(Mathf.Round(health) + " " + Mathf.Floor(health) + " " + Mathf.Ceil(health));
// Abs: the size of a number without its sign. Sign: -1, 0 or 1.
float speed = -4.5f;
Debug.Log("moving at " + Mathf.Abs(speed) + " to the " + (Mathf.Sign(speed) < 0f ? "left" : "right"));
// Min, Max: the smaller and the larger of two numbers.
float damage = Mathf.Max(0f, 30f - 12f); // armour never heals
float heal = Mathf.Min(25f, 100f - health); // never above full
// Clamp: keep a value inside a range. Clamp01: inside 0 to 1.
health = Mathf.Clamp(health - damage + heal, 0f, 100f);
float bar = Mathf.Clamp01(health / 100f);
Debug.Log("health bar " + bar);
// Sqrt: square root (the length of a 3-4-5 triangle's long side).
Debug.Log(Mathf.Sqrt(3f * 3f + 4f * 4f));
// PI, Deg2Rad, Rad2Deg: Sin, Cos and Tan take radians, so degrees are multiplied by Deg2Rad first.
float quarter = 90f * Mathf.Deg2Rad;
Debug.Log("a quarter turn is " + quarter + " = " + Mathf.PI / 2f + " radians, or " + quarter * Mathf.Rad2Deg + " degrees");
Debug.Log("tan 45 = " + Mathf.Tan(45f * Mathf.Deg2Rad));
// Atan2: the angle of a direction (y, x), in radians: which way a 2D enemy should face.
float facing = Mathf.Atan2(1f, 1f) * Mathf.Rad2Deg; // 45
Debug.Log("facing " + facing);
}
public override void Update(float deltaTime)
{
// Sin and Cos: a circle. This object goes round a 2 unit ring once every few seconds.
angle += deltaTime;
transform.position = new Vector3(Mathf.Cos(angle) * 2f, 1f, Mathf.Sin(angle) * 2f);
// PingPong: a value that goes up to the length and back down, for ever (a lift, a pulsing light).
float lift = Mathf.PingPong(Time.time, 3f);
// Exp: frame-rate independent smoothing: 1 - Exp(-speed * time) is how far to move this frame.
float follow = 1f - Mathf.Exp(-6f * deltaTime);
// Lerp: blend between two numbers; 0 gives the first, 1 the second.
float y = Mathf.Lerp(transform.position.y, 1f + lift, follow);
transform.position = new Vector3(transform.position.x, y, transform.position.z);
}
}
Keyframe
struct Keyframe
One key of an AnimationCurve: a time, the value there, and the slopes coming in and going out.
| Member | Description | Example |
|---|---|---|
float time, value, inTangent, outTangent | When the key is, the value there, and the slopes coming in and going out. | Debug.Log("from " + start.time + " s to " + end.time + " s, ending at " + end.value + " (slope in " + end.i... |
Keyframe(float time, float value) | A key with flat slopes. | Keyframe start = new Keyframe(0f, 0f); |
Keyframe(float time, float value, float inTangent, float outTangent) | A key with these slopes. | Keyframe start = new Keyframe(0f, 0f); |
Example (Keyframe.cs)
// Keyframe: one point of an AnimationCurve: a time, a value and the slopes either side.
public class KeyframeExample : Behaviour
{
public override void Start()
{
// A key with flat slopes: at 0 seconds the value is 0.
Keyframe start = new Keyframe(0f, 0f);
// A key with slopes: at 1 second the value is 1, arriving steeply (inTangent 2) and leaving flat (outTangent 0).
Keyframe end = new Keyframe(1f, 1f, 2f, 0f);
// time, value, inTangent, outTangent can be read and changed.
start.outTangent = 0f;
end.value = 1.5f;
Debug.Log("from " + start.time + " s to " + end.time + " s, ending at " + end.value + " (slope in " + end.inTangent + ", out " + end.outTangent + ")");
// Keys make a curve.
AnimationCurve jump = new AnimationCurve(start, end);
Debug.Log("half way: " + jump.Evaluate(0.5f));
}
}
AnimationCurve
class AnimationCurve
A number that changes over time (or over any input), drawn and edited in the Inspector as a curve: public AnimationCurve jump = AnimationCurve.EaseInOut(0, 0, 1, 1); then jump.Evaluate(t).
| Member | Description | Example |
|---|---|---|
Keyframe[] keys | Its keys in time order. | Debug.Log(custom.length + " keys; the new one is number " + where); |
AnimationCurve(params Keyframe[] keys) | A curve through these keys. | custom = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(0.3f, 1f), new Keyframe(1f, 0f)); |
int length | How many keys it has. | Debug.Log(custom.length + " keys; the new one is number " + where); |
float Evaluate(float t) | The value at time t: the first key's before it, the last key's after it. | float height = bounce.Evaluate(t); |
int AddKey(float time, float value) | Adds a key (flat slopes) and returns where it went. | int where = custom.AddKey(0.6f, 0.8f); |
static AnimationCurve Linear(float t0, float v0, float t1, float v1) | A straight line from (t0, v0) to (t1, v1). | fade = AnimationCurve.Linear(0f, 1f, 2f, 0f); |
static AnimationCurve EaseInOut(float t0, float v0, float t1, float v1) | From (t0, v0) to (t1, v1), starting and ending slowly. | public AnimationCurve bounce = AnimationCurve.EaseInOut(0f, 0f, 1f, 2f); |
static AnimationCurve Constant(float t0, float t1, float v) | The same value from t0 to t1. | steady = AnimationCurve.Constant(0f, 5f, 0.5f); |
Example (AnimationCurve.cs)
// AnimationCurve: a value that changes over time along a curve you design: jump heights, fades, recoil.
public class AnimationCurveExample : Behaviour
{
// A public curve shows in the Inspector with its own editor.
public AnimationCurve bounce = AnimationCurve.EaseInOut(0f, 0f, 1f, 2f); // EaseInOut: slow start, slow end
AnimationCurve fade;
AnimationCurve steady;
AnimationCurve custom;
float t;
public override void Start()
{
// Linear: a straight line from (time 0, value 1) to (time 2, value 0).
fade = AnimationCurve.Linear(0f, 1f, 2f, 0f);
// Constant: the same value the whole time.
steady = AnimationCurve.Constant(0f, 5f, 0.5f);
// The constructor takes any number of keys.
custom = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(0.3f, 1f), new Keyframe(1f, 0f));
// AddKey: one more key (flat slopes); it returns where the key went in time order.
int where = custom.AddKey(0.6f, 0.8f);
// length: how many keys. keys: the keys themselves, in time order.
Debug.Log(custom.length + " keys; the new one is number " + where);
foreach (Keyframe k in custom.keys) Debug.Log(" " + k.time + " s -> " + k.value);
}
public override void Update(float deltaTime)
{
t = (t + deltaTime) % 1f;
// Evaluate: the curve's value at a time (before the first key: its value; after the last: its value).
float height = bounce.Evaluate(t);
transform.position = new Vector3(transform.position.x, height, transform.position.z);
transform.scale = Vector3.one * (0.5f + steady.Evaluate(t) + custom.Evaluate(t) * 0.2f * fade.Evaluate(Time.time));
}
}
Time
static class Time
Frame timing.
| Member | Description | Example |
|---|---|---|
static float timeScale | How fast game time runs: 1 normal, 0.5 half speed, up to 10, 0 paused (scripts still run, with a deltaTime of 0; physics and animation stand still). Resets to 1 when the game stops. | Time.timeScale = Input.GetKey("Tab") ? 0.25f : 1f; |
static float deltaTime | Seconds since the last frame. | public override void Update(float deltaTime) |
static float unscaledDeltaTime | The same, whatever timeScale is: a pause menu's clock. | timer += Time.unscaledDeltaTime; |
static float fixedDeltaTime | The step of FixedUpdate in seconds (0.02). | float step = Time.fixedDeltaTime; |
static float time | Seconds since Play started. | if (Time.time > 3f && timer == 0f) timer = Time.time; |
static int frameCount | Frames since the game started. | if (Time.frameCount % 60 == 0) Debug.Log("frame " + Time.frameCount); |
Example (Time.cs)
// Time: frame time, game time, slow motion and the fixed step.
public class TimeExample : Behaviour
{
float timer;
public override void Update(float deltaTime)
{
// deltaTime: seconds since the last frame (already scaled by timeScale). Move by speed * time, never per frame.
transform.position += new Vector3(2f * Time.deltaTime, 0f, 0f);
// time: seconds of game time since the game started (stops while timeScale is 0).
if (Time.time > 3f && timer == 0f) timer = Time.time;
// frameCount: how many frames have been drawn.
if (Time.frameCount % 60 == 0) Debug.Log("frame " + Time.frameCount);
// timeScale: 1 is normal, 0.25 slow motion, 0 a pause. Hold Tab for slow motion.
Time.timeScale = Input.GetKey("Tab") ? 0.25f : 1f;
// unscaledDeltaTime: real seconds since the last frame, for menus that must move while the game is paused.
timer += Time.unscaledDeltaTime;
}
public override void FixedUpdate()
{
// fixedDeltaTime: the length of one physics step (1/50 s): use it inside FixedUpdate.
float step = Time.fixedDeltaTime;
transform.position += new Vector3(0f, 0f, 1f * step);
}
}
Audio
static class Audio
Sound from scripts: play any project sound (.wav, .ogg, .mp3 or .flac) with a volume, a pitch and a loop, and change or stop it later by the handle Play returned. Sounds on the SFX bus unless told otherwise.
| Member | Description | Example |
|---|---|---|
static int Play(string clip, float volume = 1f, float pitch = 1f, bool loop = false, string bus = "SFX") | Plays a sound file, e.g. Audio.Play("Audio/Coin.wav"). Returns a handle for Stop, SetVolume and SetPitch. pitch 1 is normal speed, 2 an octave up; loop repeats until stopped. | Audio.Play("Audio/coin.wav"); |
static int PlayAt(string clip, Vector3 position, float volume = 1f, float pitch = 1f, float radius = 40f, bool loop = false, string bus = "SFX") | Plays a sound from a place in the world: it is quieter and panned with distance from the camera. | siren = Audio.PlayAt("Audio/siren.wav", new Vector3(20f, 0f, 5f), 1f, 1f, 60f, true); |
static void SetVolume(int handle, float volume) | Changes the volume (0..1) of a playing sound. | Audio.SetVolume(engine, Mathf.Clamp01(0.3f + carSpeed * 0.01f)); |
static void SetPitch(int handle, float pitch) | Changes the pitch of a playing sound (an engine note follows the speed this way). | Audio.SetPitch(engine, 0.8f + carSpeed * 0.02f); |
static void SetPosition(int handle, Vector3 position) | Moves a world sound (see PlayAt). | Audio.SetPosition(siren, new Vector3(20f - Time.time * 5f, 0f, 5f)); |
static void Restart(GameObject go) | Plays the object's AudioSource again from the start. | Audio.Restart(gameObject); |
static void Stop(int handle) | Stops one sound. | if (Input.GetKeyDown("M")) Audio.Stop(engine); |
static void StopAll() | Stops every sound the scripts started. | if (Input.GetKeyDown("Escape")) Audio.StopAll(); |
Example (Audio.cs)
// Audio: playing sounds from a script: one-shots, loops, sounds at a place in the world.
public class AudioExample : Behaviour
{
public float carSpeed;
int engine;
int siren;
public override void Start()
{
// Play: plays a sound file once and returns a handle. Volume 0..1, pitch 1 = as recorded, loop, and a mixer bus.
Audio.Play("Audio/coin.wav");
// A looping sound on the Music bus, kept by its handle so it can be changed later.
engine = Audio.Play("Audio/engine.wav", 0.6f, 1f, true, "SFX");
// PlayAt: a sound from a place in the world: quieter and panned with distance; heard up to the radius.
siren = Audio.PlayAt("Audio/siren.wav", new Vector3(20f, 0f, 5f), 1f, 1f, 60f, true);
// Restart: plays this object's own AudioSource component again from the start.
Audio.Restart(gameObject);
}
public override void Update(float deltaTime)
{
// SetPitch: an engine note that follows the speed.
Audio.SetPitch(engine, 0.8f + carSpeed * 0.02f);
// SetVolume: louder when faster.
Audio.SetVolume(engine, Mathf.Clamp01(0.3f + carSpeed * 0.01f));
// SetPosition: move a world sound (the siren drives past).
Audio.SetPosition(siren, new Vector3(20f - Time.time * 5f, 0f, 5f));
// Stop: one sound, by its handle.
if (Input.GetKeyDown("M")) Audio.Stop(engine);
// StopAll: every sound the scripts started (going back to the menu).
if (Input.GetKeyDown("Escape")) Audio.StopAll();
}
}
Scene
static class Scene
Changing scenes: scenes are the ones in the build settings (by name, e.g. "Level2", or by index). Works in the built game, in the player and in the editor's Play mode (Stop brings back the scene being edited).
| Member | Description | Example |
|---|---|---|
static void Load(string name) | Loads a scene by name ("Level2") or build index. | if (Input.GetKeyDown("1")) Scene.Load("Level2"); |
static void Load(int index) | Loads a scene by its number in the build settings (0 is the first). | if (Input.GetKeyDown("1")) Scene.Load("Level2"); |
static void Next() | The next scene in the build settings. | if (Input.GetKeyDown("N")) Scene.Next(); |
static void Previous() | The scene before this one in the build settings. | if (Input.GetKeyDown("P")) Scene.Previous(); |
static void Reload() | Starts the current scene again. | if (transform.position.y < -20f) Scene.Reload(); |
static SceneLoad LoadAsync(string name) | Loads a scene in the background while this one keeps running: its models and pictures are read on other threads, and it starts once they are in (hold it with SceneLoad.allowSceneActivation). Show a loading bar with SceneLoad.progress, or yield return it in a coroutine. | SceneLoad load = Scene.LoadAsync("Level3"); |
static SceneLoad LoadAsync(int index) | Loads the scene with this number in the build settings in the background (see LoadAsync(string)). | SceneLoad load = Scene.LoadAsync("Level3"); |
Example (Scene.cs)
// Scene: moving between the scenes listed in Build Settings.
using System.Collections;
public class SceneExample : Behaviour
{
public override void Update(float deltaTime)
{
// Load: by name, or by its number in the build settings (0 is the first).
if (Input.GetKeyDown("1")) Scene.Load("Level2");
if (Input.GetKeyDown("0")) Scene.Load(0);
// Next and Previous: the scene after and before this one in the build settings.
if (Input.GetKeyDown("N")) Scene.Next();
if (Input.GetKeyDown("P")) Scene.Previous();
// Reload: start this scene again (the player fell off the level).
if (transform.position.y < -20f) Scene.Reload();
if (Input.GetKeyDown("L")) StartCoroutine(LoadBehindAScreen());
}
IEnumerator LoadBehindAScreen()
{
// LoadAsync: loads in the background while this scene keeps running (by name or by index).
SceneLoad load = Scene.LoadAsync("Level3");
while (!load.isDone)
{
UI.SetText("Loading", "Loading " + Mathf.RoundToInt(load.progress * 100f) + "%");
yield return null;
}
// The index form does the same for the scene with that number.
SceneLoad warm = Scene.LoadAsync(2);
yield return warm;
}
}
SceneLoad
class SceneLoad
A scene loading in the background, as Scene.LoadAsync(string) returns it.
| Member | Description | Example |
|---|---|---|
float progress | How much of the scene's models and pictures is loaded, from 0 to 1. | UI.SetValue("LoadBar", load.progress); |
bool isDone | True once everything is loaded: the scene starts after this frame, unless allowSceneActivation is false. | while (!load.isDone) |
bool allowSceneActivation | Whether the scene may start as soon as it is loaded (true at first). Set it to false to keep it waiting, loaded, until you set it back to true ("press any key to continue"). | load.allowSceneActivation = false; |
Example (SceneLoad.cs)
// SceneLoad: a scene loading in the background: a progress bar, and holding the scene back until the player is ready.
using System.Collections;
public class SceneLoadExample : Behaviour
{
IEnumerator Start()
{
SceneLoad load = Scene.LoadAsync("Level2");
// allowSceneActivation: false keeps the loaded scene waiting instead of starting it.
load.allowSceneActivation = false;
// progress: how much is loaded, 0 to 1. isDone: true once everything is in.
while (!load.isDone)
{
UI.SetValue("LoadBar", load.progress);
yield return null;
}
UI.SetText("Hint", "Press Space to start");
yield return new WaitUntil(() => Input.GetKeyDown("Space"));
load.allowSceneActivation = true; // now the scene starts
}
}
ContentPacks
static class ContentPacks
Content packs the game downloads while it plays: scenes, prefabs, models, pictures, materials and sounds that are not in the build, packed with neux content-pack and put on a web server. Once a pack is in, its files load like the game's own: Scene.Load("Scenes/Bonus.scene"), a prefab, a model. Scripts are not packed (the game runs the scripts it was built with). A native game keeps what it downloaded in its own folder; asking again for a URL this run already has does not download it again.
| Member | Description | Example |
|---|---|---|
static ContentPack Download(string url, string sha256 = null) | Starts downloading the pack at url (http:// or https://). Watch ContentPack.progress, or yield return it in a coroutine. With sha256 (the file's SHA-256 in hex) a pack that does not match is refused, so a swapped file never reaches the game. | ContentPack pack = ContentPacks.Download("https: |
Example (ContentPacks.cs)
// ContentPacks: downloading extra content (levels, models, sounds) after the game has shipped.
using System.Collections;
public class ContentPacksExample : Behaviour
{
IEnumerator Start()
{
// Download: starts fetching a pack made with `neux content-pack`. The SHA-256 (optional) makes sure it is the right file.
ContentPack pack = ContentPacks.Download("https://example.com/packs/winter.neuxpack", "9f2c0e1d4b7a8c3f5e6d0a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f");
yield return pack; // wait for it
if (pack.isReady) Scene.Load("Winter"); // its scenes load like any other
}
}
ContentPack
class ContentPack
A content pack downloading, as ContentPacks.Download(string) returns it.
| Member | Description | Example |
|---|---|---|
string url | Where it comes from. | Debug.Log("downloading " + pack.url); |
float progress | How much of it is in, from 0 to 1 (0 until the end when the server does not say its size). | UI.SetValue("DownloadBar", pack.progress); |
bool isDone | True once the download is over, whether it worked or not (see error). | while (!pack.isDone) |
string error | Why it failed, or null. | if (pack.error != null) UI.SetText("Status", "Download failed: " + pack.error); |
bool isReady | True once its files can be loaded. | else if (pack.isReady) UI.SetText("Status", "Desert levels are ready"); |
Example (ContentPack.cs)
// ContentPack: one download in progress: how far it is, whether it worked, and why not.
using System.Collections;
public class ContentPackExample : Behaviour
{
IEnumerator Start()
{
ContentPack pack = ContentPacks.Download("https://example.com/packs/desert.neuxpack");
// url: where it comes from.
Debug.Log("downloading " + pack.url);
// isDone: true when the download is over, whether it worked or not. progress: 0 to 1.
while (!pack.isDone)
{
UI.SetValue("DownloadBar", pack.progress);
yield return null;
}
// error: why it failed, or null. isReady: its files can be loaded now.
if (pack.error != null) UI.SetText("Status", "Download failed: " + pack.error);
else if (pack.isReady) UI.SetText("Status", "Desert levels are ready");
}
}
Application
static class Application
The running game.
| Member | Description | Example |
|---|---|---|
static void Quit() | Closes the built game (in the editor it stops Play). | if (Input.GetKeyDown("Escape")) Application.Quit(); |
static string platform | What the game runs on: "macOS", "Windows", "Linux", "iOS", "Android" or "Web". | Debug.Log("running on " + Application.platform); |
static bool isMobilePlatform | True on a phone or tablet (iOS, Android). | UI.SetVisible("TouchControls", Application.isMobilePlatform); |
static string version | The game's version, as set in Project Settings > Player ("" when none is set). | UI.SetText("Title", Application.productName + " " + Application.version); |
static string productName | The game's product name, as set in Project Settings > Player. | UI.SetText("Title", Application.productName + " " + Application.version); |
static bool isEditor | True while the game runs inside the editor (Play), false in a built game. | UI.SetVisible("DebugPanel", Application.isEditor); |
Example (Application.cs)
// Application: what the game is running on, its name and version, and closing it.
public class ApplicationExample : Behaviour
{
public override void Start()
{
// productName and version: from Project Settings > Player.
UI.SetText("Title", Application.productName + " " + Application.version);
// platform: "macOS", "Windows", "Linux", "iOS", "Android" or "Web".
Debug.Log("running on " + Application.platform);
// isMobilePlatform: true on a phone or tablet: show the touch controls there.
UI.SetVisible("TouchControls", Application.isMobilePlatform);
// isEditor: true while playing inside the editor: handy for cheats and debug text that must not ship.
UI.SetVisible("DebugPanel", Application.isEditor);
}
public override void Update(float deltaTime)
{
// Quit: closes the built game (in the editor it stops Play).
if (Input.GetKeyDown("Escape")) Application.Quit();
}
}
CursorLockMode
enum CursorLockMode
How the mouse pointer is held by the game window.
| Member | Description | Example |
|---|---|---|
None | The pointer moves freely. | if (Input.GetKeyDown("Escape")) Cursor.lockState = CursorLockMode.None; |
Locked | The pointer is locked in place and hidden-friendly: only Input.mouseDelta moves (first-person look). | if (Input.GetMouseButtonDown(0)) Cursor.lockState = CursorLockMode.Locked; |
Confined | The pointer cannot leave the window. | if (Input.GetKeyDown("C")) Cursor.lockState = CursorLockMode.Confined; |
Example (CursorLockMode.cs)
// CursorLockMode: the three ways the game can hold the mouse pointer.
public class CursorLockModeExample : Behaviour
{
public override void Update(float deltaTime)
{
// Locked: the pointer stays put and only Input.mouseDelta moves: first-person looking.
if (Input.GetMouseButtonDown(0)) Cursor.lockState = CursorLockMode.Locked;
// Confined: the pointer moves but cannot leave the window: a strategy game that scrolls at the edges.
if (Input.GetKeyDown("C")) Cursor.lockState = CursorLockMode.Confined;
// None: the pointer is free again: menus.
if (Input.GetKeyDown("Escape")) Cursor.lockState = CursorLockMode.None;
}
}
Cursor
static class Cursor
The mouse pointer: show, hide, lock. Play mode gives it back when it stops.
| Member | Description | Example |
|---|---|---|
static bool visible | Whether the pointer is drawn. | Cursor.visible = false; |
static CursorLockMode LockState | Whether the pointer is free, locked or confined. | Cursor.LockState = paused ? CursorLockMode.None : CursorLockMode.Locked; |
static CursorLockMode lockState | Whether the pointer is free, locked or confined. | Cursor.lockState = CursorLockMode.Locked; |
Example (Cursor.cs)
// Cursor: showing, hiding and locking the mouse pointer.
public class CursorExample : Behaviour
{
bool paused;
public override void Start()
{
// A first-person game starts with the pointer hidden and locked.
// visible: whether the pointer is drawn. lockState: free, locked or confined.
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
public override void Update(float deltaTime)
{
if (!Input.GetKeyDown("Escape")) return;
paused = !paused;
// The pause menu needs the pointer back.
Cursor.visible = paused;
// LockState is the same setting as lockState (either spelling works).
Cursor.LockState = paused ? CursorLockMode.None : CursorLockMode.Locked;
Debug.Log("pointer is " + Cursor.lockState + ", visible " + Cursor.visible);
}
}
Screen
static class Screen
The size of the game view.
| Member | Description | Example |
|---|---|---|
static int width | Width of the game view in pixels. | Vector3 centre = new Vector3(Screen.width / 2f, Screen.height / 2f, 0f); |
static int height | Height of the game view in pixels. | Vector3 centre = new Vector3(Screen.width / 2f, Screen.height / 2f, 0f); |
static float aspect | Width divided by height (above 1: landscape). | bool wide = Screen.aspect > 2f; |
static bool portrait | True when the view is taller than it is wide (a phone held upright). | UI.SetVisible("SideBar", !Screen.portrait); |
Example (Screen.cs)
// Screen: the size and shape of the game view.
public class ScreenExample : Behaviour
{
public override void Update(float deltaTime)
{
// width, height: the game view in pixels.
Vector3 centre = new Vector3(Screen.width / 2f, Screen.height / 2f, 0f);
// aspect: width divided by height (16:9 is about 1.78).
bool wide = Screen.aspect > 2f;
// portrait: true when the view is taller than it is wide (a phone held upright).
UI.SetVisible("SideBar", !Screen.portrait);
UI.SetVisible("BottomBar", Screen.portrait);
if (Input.GetMouseButtonDown(0))
Debug.Log("clicked " + (Input.mousePosition - centre) + " from the middle of a " + (wide ? "wide" : "normal") + " screen");
}
}
SaveGame
static class SaveGame
Saved games in slots ("1", "2", "autosave", "checkpoint"...) that survive restarts: on a computer or phone in the game's own save file, on the web in the browser. A slot holds a SaveData of numbers, text and positions, and can hold where every object is.
| Member | Description | Example |
|---|---|---|
static void Save(string slot, SaveData data) | Writes data to slot, replacing what was there, and the time it was saved. | SaveGame.Save(slot, d); |
static SaveData Load(string slot) | What slot holds (an empty SaveData when it holds nothing). | SaveData d = SaveGame.Load(slot); |
static bool Exists(string slot) | True when slot has been saved to. | if (!SaveGame.Exists(slot)) { Debug.Log("slot " + slot + " is empty"); return; } |
static void Delete(string slot) | Empties slot. | if (Input.GetKeyDown("Delete")) SaveGame.Delete("1"); |
static string[] Slots() | The slots that hold a save, newest first. | foreach (string slot in SaveGame.Slots()) |
static DateTime SavedAt(string slot) | When slot was last saved (UTC; DateTime.MinValue when never). | Debug.Log("slot " + slot + " saved " + SaveGame.SavedAt(slot).ToLocalTime()); |
static void SaveObjects(string slot, SaveData extra = null) | Saves where every named object is, how it is turned and sized, and whether it is on, with extra (the score, the inventory...) beside it. | SaveGame.SaveObjects("checkpoint", d); |
static SaveData LoadObjects(string slot) | Puts every named object back where SaveObjects saved it, and returns the slot's data (its extra values). | SaveData d = SaveGame.LoadObjects("checkpoint"); |
Example (SaveGame.cs)
// SaveGame: whole saved games in slots that survive restarts, with where every object is.
public class SaveGameExample : Behaviour
{
public int coins;
public string level = "Caves";
public void SaveTo(string slot)
{
SaveData d = new SaveData();
d.SetInt("coins", coins);
d.SetString("level", level);
// Save: writes the values to a slot (any name: "1", "2", "autosave"), replacing what was there.
SaveGame.Save(slot, d);
}
public void Checkpoint()
{
SaveData d = new SaveData();
d.SetInt("coins", coins);
// SaveObjects: the values plus where every named object is, how it is turned and sized, and whether it is on.
SaveGame.SaveObjects("checkpoint", d);
}
public void LoadFrom(string slot)
{
// Exists: has this slot been saved to?
if (!SaveGame.Exists(slot)) { Debug.Log("slot " + slot + " is empty"); return; }
// Load: the slot's values (an empty SaveData when it holds nothing).
SaveData d = SaveGame.Load(slot);
coins = d.GetInt("coins");
level = d.GetString("level", "Caves");
}
public void BackToCheckpoint()
{
// LoadObjects: puts every named object back where SaveObjects saved it, and returns the slot's values.
SaveData d = SaveGame.LoadObjects("checkpoint");
coins = d.GetInt("coins");
}
public override void Start()
{
// Slots: the slots that hold a save, newest first. SavedAt: when a slot was last saved (UTC).
foreach (string slot in SaveGame.Slots())
Debug.Log("slot " + slot + " saved " + SaveGame.SavedAt(slot).ToLocalTime());
}
public override void Update(float deltaTime)
{
if (Input.GetKeyDown("F5")) SaveTo("1");
if (Input.GetKeyDown("F9")) LoadFrom("1");
// Delete: empties a slot.
if (Input.GetKeyDown("Delete")) SaveGame.Delete("1");
}
}
SaveData
class SaveData
The values of one saved game: numbers, text, switches and positions by name.
| Member | Description | Example |
|---|---|---|
void SetInt(string key, int value) | Keeps a whole number. | d.SetInt("coins", coins); |
void SetFloat(string key, float value) | Keeps a number. | d.SetFloat("health", health); |
void SetString(string key, string value) | Keeps text. | d.SetString("level", "Caves"); |
void SetBool(string key, bool value) | Keeps a yes or no. | d.SetBool("hasKey", hasKey); |
void SetVector3(string key, Vector3 v) | Keeps a position, rotation or colour as three numbers. | d.SetVector3("spawn", transform.position); |
int GetInt(string key, int fallback = 0) | A whole number, or fallback. | coins = back.GetInt("coins"); |
float GetFloat(string key, float fallback = 0f) | A number, or fallback. | health = back.GetFloat("health", 100f); |
string GetString(string key, string fallback = "") | Text, or fallback. | string level = back.GetString("level", "Meadow"); |
bool GetBool(string key, bool fallback = false) | A yes or no, or fallback. | hasKey = back.GetBool("hasKey"); |
Vector3 GetVector3(string key, Vector3 fallback = default) | Three numbers, or fallback. | transform.position = back.GetVector3("spawn", Vector3.zero); |
bool Has(string key) | True when key has a value. | if (back.Has("oldSetting")) back.Remove("oldSetting"); |
void Remove(string key) | Forgets key. | if (back.Has("oldSetting")) back.Remove("oldSetting"); |
string[] Keys | Every key that has a value. | Debug.Log(level + " holds " + back.Keys.Length + " values: " + string.Join(", ", back.Keys)); |
Example (SaveData.cs)
// SaveData: the values of one saved game: numbers, text, switches and positions by name.
public class SaveDataExample : Behaviour
{
public int coins = 12;
public float health = 64.5f;
public bool hasKey = true;
public override void Start()
{
SaveData d = new SaveData();
// SetInt, SetFloat, SetString, SetBool, SetVector3: keep a value under a name.
d.SetInt("coins", coins);
d.SetFloat("health", health);
d.SetString("level", "Caves");
d.SetBool("hasKey", hasKey);
d.SetVector3("spawn", transform.position);
SaveGame.Save("1", d);
SaveData back = SaveGame.Load("1");
// GetInt, GetFloat, GetString, GetBool, GetVector3: read a value, or the fallback when it was never saved.
coins = back.GetInt("coins");
health = back.GetFloat("health", 100f);
string level = back.GetString("level", "Meadow");
hasKey = back.GetBool("hasKey");
transform.position = back.GetVector3("spawn", Vector3.zero);
// Has: is there a value under this name? Remove: forget one.
if (back.Has("oldSetting")) back.Remove("oldSetting");
// Keys: every name that has a value.
Debug.Log(level + " holds " + back.Keys.Length + " values: " + string.Join(", ", back.Keys));
}
}
PlayerPrefs
static class PlayerPrefs
Saved settings and progress that survive restarts: best times, volume, unlocked levels.
| Member | Description | Example |
|---|---|---|
static void Save() | Writes the saved values to disk (every Set already does). | PlayerPrefs.Save(); |
static void SetInt(string key, int value) | Saves a whole number under a name. | PlayerPrefs.SetInt("unlockedLevel", PlayerPrefs.GetInt("unlockedLevel", 1) + 1); |
static void SetFloat(string key, float value) | Saves a decimal number under a name. | if (raceTime < PlayerPrefs.GetFloat("bestTime", 9999f)) PlayerPrefs.SetFloat("bestTime", raceTime); |
static void SetString(string key, string value) | Saves a piece of text under a name. | PlayerPrefs.SetString("playerName", "Ana"); |
static int GetInt(string key, int fallback = 0) | The saved whole number, or the fallback when there is none. | int level = PlayerPrefs.GetInt("unlockedLevel", 1); |
static float GetFloat(string key, float fallback = 0f) | The saved decimal number, or the fallback when there is none. | float volume = PlayerPrefs.GetFloat("volume", 0.8f); |
static string GetString(string key, string fallback = "") | The saved text, or the fallback when there is none. | string name = PlayerPrefs.GetString("playerName", "Player"); |
static bool HasKey(string key) | True when something is saved under this name. | if (!PlayerPrefs.HasKey("bestTime")) Debug.Log("no best time yet"); |
static void DeleteKey(string key) | Forgets what was saved under this name. | PlayerPrefs.DeleteKey("bestTime"); |
Example (PlayerPrefs.cs)
// PlayerPrefs: small settings and progress that survive restarts: volume, best time, the player's name.
public class PlayerPrefsExample : Behaviour
{
float raceTime;
public override void Start()
{
// GetFloat, GetInt, GetString: read a saved value, or the fallback when nothing is saved yet.
float volume = PlayerPrefs.GetFloat("volume", 0.8f);
int level = PlayerPrefs.GetInt("unlockedLevel", 1);
string name = PlayerPrefs.GetString("playerName", "Player");
Debug.Log(name + " has unlocked level " + level + "; volume " + volume);
// HasKey: is anything saved under this name?
if (!PlayerPrefs.HasKey("bestTime")) Debug.Log("no best time yet");
}
public void FinishRace()
{
// SetFloat, SetInt, SetString: save a value (each Set writes to disk).
if (raceTime < PlayerPrefs.GetFloat("bestTime", 9999f)) PlayerPrefs.SetFloat("bestTime", raceTime);
PlayerPrefs.SetInt("unlockedLevel", PlayerPrefs.GetInt("unlockedLevel", 1) + 1);
PlayerPrefs.SetString("playerName", "Ana");
// Save: writes everything now (already done by each Set; here for clarity before quitting).
PlayerPrefs.Save();
}
public void ResetProgress()
{
// DeleteKey: forget one saved value.
PlayerPrefs.DeleteKey("bestTime");
PlayerPrefs.DeleteKey("unlockedLevel");
}
public override void Update(float deltaTime) { raceTime += deltaTime; }
}
NeuxDebug
static class NeuxDebug
The editor's breakpoint call: the build inserts NeuxDebug.Hit("File.cs", line); before each breakpoint line. Play pauses there until Resume.
| Member | Description | Example |
|---|---|---|
static void Hit(string file, int line) | Called by the debugger hooks at each line; not for scripts. | if (false) NeuxDebug.Hit("Scripts/NeuxDebugExample.cs", 12); |
Example (NeuxDebug.cs)
// NeuxDebug: the call the editor puts before a line that has a breakpoint. Scripts do not call it themselves.
public class NeuxDebugExample : Behaviour
{
int hits;
public override void Update(float deltaTime)
{
hits++;
// With a breakpoint on the next line, the editor compiles the script as if this call were written here:
// Play pauses on that line until Resume is pressed. Set breakpoints by clicking the margin in the code editor.
if (false) NeuxDebug.Hit("Scripts/NeuxDebugExample.cs", 12);
if (hits > 100) hits = 0;
}
}
Localization
static class Localization
Localized text from the project's string tables (Localization/*.csv: key, then one column per language).
| Member | Description | Example |
|---|---|---|
static string language | The language the game runs in (a column code: "en", "es", ...). Setting it switches every text at once, labels in the game's UI included (for the rest of the game, or until Play stops in the editor). | Debug.Log("language " + Localization.language + " of " + string.Join(", ", Localization.languages)); |
static string[] languages | The languages the game's tables have (the column codes). | Debug.Log("language " + Localization.language + " of " + string.Join(", ", Localization.languages)); |
static string Get(string key) | The text for key; the key itself when the tables have no such entry (so missing text is easy to spot). | UI.SetText("PlayButton", Localization.Get("menu.play")); |
static string Get(string key, params object[] args) | The text with {0}, {1}, ... filled in from args. | UI.SetText("PlayButton", Localization.Get("menu.play")); |
static bool Has(string key) | True when the tables have text for the key. | if (!Localization.Has("menu.credits")) Debug.LogWarning("menu.credits is not translated yet"); |
static string GetPlural(string key, double n, params object[] args) | The text for a count: the row "key#one", "key#few"... the language's rules pick for n (else "key#other", else "key"), with {0} = n and {1}... from args. | UI.SetText("Coins", Localization.GetPlural("coins", coins)); |
static string PluralCategory(double n) | "zero", "one", "two", "few", "many" or "other" for a count in the current language. | Debug.Log(coins + " is '" + Localization.PluralCategory(coins) + "'"); |
Example (Localization.cs)
// Localization: text in the player's language from the string tables in Localization/*.csv.
public class LocalizationExample : Behaviour
{
public int coins = 5;
public override void Start()
{
// language: the language the game runs in. languages: every column the tables have.
Debug.Log("language " + Localization.language + " of " + string.Join(", ", Localization.languages));
// Get: the text for a key (the key itself when the tables have none, so missing text is easy to spot).
UI.SetText("PlayButton", Localization.Get("menu.play"));
// Get with arguments fills {0}, {1}... in the text: "Hello, {0}!"
UI.SetText("Greeting", Localization.Get("menu.greeting", "Ana"));
// Has: is there text for this key?
if (!Localization.Has("menu.credits")) Debug.LogWarning("menu.credits is not translated yet");
// GetPlural: picks the row for the count ("coins#one", "coins#few", "coins#other"...) by the language's rules.
UI.SetText("Coins", Localization.GetPlural("coins", coins));
// PluralCategory: which of zero, one, two, few, many, other a count is in this language.
Debug.Log(coins + " is '" + Localization.PluralCategory(coins) + "'");
}
public override void Update(float deltaTime)
{
// Setting language switches every text at once, labels in the game's UI included.
if (Input.GetKeyDown("F2"))
{
int next = (System.Array.IndexOf(Localization.languages, Localization.language) + 1) % Localization.languages.Length;
Localization.language = Localization.languages[next];
}
}
}
Debug
static class Debug
Writes to the editor console.
| Member | Description | Example |
|---|---|---|
static void Log(object message) | Logs a message. | Debug.Log("spawned at " + transform.position); |
static void LogWarning(object message) | Logs a warning. | if (target == null) Debug.LogWarning("no target set on " + gameObject.name + ": it will stand still"); |
static void LogError(object message) | Logs an error. | Debug.LogError("health went below zero: " + health); |
static void Break() | Pauses play mode in the editor at the end of this frame: inspect the scene, then press Play or Step. | Debug.Break(); |
Example (Debug.cs)
// Debug: messages for the editor's Console, and pausing Play from a script.
public class DebugExample : Behaviour
{
public GameObject target;
public float health = 100f;
public override void Start()
{
// Log: a plain message (any value: text, numbers, vectors).
Debug.Log("spawned at " + transform.position);
// LogWarning: something looks wrong but the game goes on (yellow in the Console).
if (target == null) Debug.LogWarning("no target set on " + gameObject.name + ": it will stand still");
}
public override void Update(float deltaTime)
{
if (health < 0f)
{
// LogError: something is broken (red in the Console; ERROR PAUSE stops Play on it).
Debug.LogError("health went below zero: " + health);
// Break: pauses Play at the end of this frame so the scene can be looked at; press Play to go on.
Debug.Break();
health = 0f;
}
}
}
UIElement
class UIElement
A UI object a script holds in a field (UIButton, UIText and the rest), set in the Inspector or dropped there from the Hierarchy: it is found by its id, whatever its name and however many objects share that name.
| Member | Description | Example |
|---|---|---|
GameObject gameObject | The object this is, when it is also a scene object scripts see (a UI object may not be). | Debug.Log("the banner is " + banner.name + (banner.gameObject != null ? " (a scene object too)" : "")); |
string name | The object's name. | Debug.Log("the banner is " + banner.name + (banner.gameObject != null ? " (a scene object too)" : "")); |
bool visible | Shown, or hidden with everything under it. | banner.visible = true; |
Vector2 position | Its offset from its anchor in canvas units (x right, y down), as in its Rect. | banner.position = new Vector2(0f, 40f); |
Vector2 size | Its width and height in canvas units. | banner.size = new Vector2(420f, 80f); |
float rotation | Its turn in degrees, counter-clockwise, about its middle. | banner.rotation = 0f; |
Color color | A label's text colour, a picture's tint, else a panel's colour. | banner.color = new Color(0f, 0f, 0f, 0.6f); |
Example (UIElement.cs)
// UIElement: what every UI field a script holds shares (UIButton, UIText and the rest): set in the Inspector, or dropped
// there from the Hierarchy, it finds its object by id, whatever its name.
public class UIElementExample : Behaviour
{
public UIElement banner;
public override void Start()
{
// name: the object's name; gameObject: the scene object (null when the UI object is not one scripts see).
Debug.Log("the banner is " + banner.name + (banner.gameObject != null ? " (a scene object too)" : ""));
// visible: shown, or hidden with everything under it.
banner.visible = true;
// position and size: canvas units, x right and y down, from its anchor as in its Rect.
banner.position = new Vector2(0f, 40f);
banner.size = new Vector2(420f, 80f);
// rotation: degrees, counter-clockwise, about its middle. color: text colour, tint or panel colour.
banner.rotation = 0f;
banner.color = new Color(0f, 0f, 0f, 0.6f);
}
}
UIEvent
class UIEvent
Something a UI object does that scripts can listen for: play.onClick += Begin; or play.onClick.AddListener(Begin);.
| Member | Description | Example |
|---|---|---|
void AddListener(Action call) | Calls call each time it happens. | start.onClick.AddListener(Begin); |
void RemoveListener(Action call) | Stops calling call. | start.onClick.RemoveListener(Begin); |
void RemoveAllListeners() | Stops every call added to it. | quit.onClick.RemoveAllListeners(); |
static UIEvent operator +(UIEvent e, Action call) | The same as AddListener: button.onClick += Begin; | |
static UIEvent operator -(UIEvent e, Action call) | The same as RemoveListener: button.onClick -= Begin; |
Example (UIEvent.cs)
// UIEvent: something a UI object does that a script listens for (a button's onClick, a toggle's onValueChanged, an
// input's onSubmit).
public class UIEventExample : Behaviour
{
public UIButton start;
public UIButton quit;
public override void Start()
{
// AddListener (or +=): call this each time it happens.
start.onClick.AddListener(Begin);
quit.onClick += Leave;
}
void Begin()
{
// RemoveListener (or -=): stop calling it. RemoveAllListeners: stop every call added.
start.onClick.RemoveListener(Begin);
quit.onClick -= Leave;
quit.onClick.RemoveAllListeners();
Scene.Load("Level1");
}
void Leave() { Application.Quit(); }
}
UIButton
class UIButton : UIElement
A button a script holds in a field: public UIButton play; then play.onClick += Begin;.
| Member | Description | Example |
|---|---|---|
UIEvent onClick | What a click calls (its On Click list in the Inspector calls its own as well). | play.onClick += () => presses++; |
bool clicked | True on the frame it was clicked. | if (play.clicked) Debug.Log("pressed " + presses + " times"); |
Example (UIButton.cs)
// UIButton: a button a script holds in a field. Drop the button on the field in the Inspector; two buttons may share a name.
public class UIButtonExample : Behaviour
{
public UIButton play;
int presses;
public override void Start()
{
// onClick: what a click calls (the button's own On Click list in the Inspector runs as well).
play.onClick += () => presses++;
}
public override void Update(float deltaTime)
{
// clicked: true on the frame it was clicked.
if (play.clicked) Debug.Log("pressed " + presses + " times");
}
}
UIText
class UIText : UIElement
A text (UI Label) a script holds in a field: public UIText score; then score.text = "10";.
| Member | Description | Example |
|---|---|---|
string text | The words it shows (setting them stops it following its localization key). | score.text = "Score " + points; |
Example (UIText.cs)
// UIText: a label a script holds in a field: its words change without looking it up by name.
public class UITextExample : Behaviour
{
public UIText score;
int points;
public void AddPoint()
{
points++;
// text: the words it shows.
score.text = "Score " + points;
if (score.text.Length > 12) Debug.Log("a long score");
}
}
UIImage
class UIImage : UIElement
A picture (UI Image) a script holds in a field.
| Member | Description | Example |
|---|---|---|
string image | The picture it shows, a project path such as "Textures/arrow.png". | portrait.image = hurt ? "Textures/hero-hurt.png" : "Textures/hero.png"; |
Example (UIImage.cs)
// UIImage: a picture a script holds in a field.
public class UIImageExample : Behaviour
{
public UIImage portrait;
public void ShowHero(bool hurt)
{
// image: the picture it shows, a project path.
portrait.image = hurt ? "Textures/hero-hurt.png" : "Textures/hero.png";
Debug.Log("showing " + portrait.image);
}
}
UISlider
class UISlider : UIElement
A slider or progress bar a script holds in a field.
| Member | Description | Example |
|---|---|---|
float value | Its value. | health.value = Mathf.Max(0f, health.value - damage); |
Example (UISlider.cs)
// UISlider: a slider or a progress bar a script holds in a field.
public class UISliderExample : Behaviour
{
public UISlider health;
public void Hit(float damage)
{
// value: where it stands.
health.value = Mathf.Max(0f, health.value - damage);
}
}
UIToggle
class UIToggle : UIElement
A toggle (checkbox) a script holds in a field.
| Member | Description | Example |
|---|---|---|
bool isOn | Whether it is checked. | music.isOn = true; |
UIEvent onValueChanged | What a click on it calls. | music.onValueChanged += () => PlayerPrefs.SetInt("music", music.isOn ? 1 : 0); |
Example (UIToggle.cs)
// UIToggle: a checkbox a script holds in a field.
public class UIToggleExample : Behaviour
{
public UIToggle music;
public override void Start()
{
// isOn: whether it is checked. onValueChanged: what a click on it calls.
music.isOn = true;
music.onValueChanged += () => PlayerPrefs.SetInt("music", music.isOn ? 1 : 0);
}
}
UIInput
class UIInput : UIElement
A text input a script holds in a field.
| Member | Description | Example |
|---|---|---|
string text | What is typed in it. | playerName.text = PlayerPrefs.GetString("name"); |
UIEvent onSubmit | What Enter in it calls. | playerName.onSubmit += () => PlayerPrefs.SetString("name", playerName.text); |
Example (UIInput.cs)
// UIInput: a text input a script holds in a field.
public class UIInputExample : Behaviour
{
public UIInput playerName;
public override void Start()
{
// text: what is typed in it. onSubmit: what Enter in it calls.
playerName.text = PlayerPrefs.GetString("name");
playerName.onSubmit += () => PlayerPrefs.SetString("name", playerName.text);
}
}
Random
static class Random
Random numbers.
| Member | Description | Example |
|---|---|---|
static float value | A random number from 0 up to 1. | bool rare = Random.value < 0.2f; |
static float Range(float lo, float hi) | A random number from lo up to hi. | Vector3 place = new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f)); |
static int Range(int lo, int hiExclusive) | A random whole number from lo up to (not including) hiExclusive. | Vector3 place = new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f)); |
Example (Random.cs)
// Random: chance: where things spawn, what drops, how much damage.
public class RandomExample : Behaviour
{
public string[] shapes = { "Cube", "Sphere", "Capsule" };
public override void Start()
{
for (int i = 0; i < 10; i++)
{
// Range with floats: a number from the first up to the second.
Vector3 place = new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f));
// Range with ints: a whole number from the first up to, not including, the second: a random array index.
string shape = shapes[Random.Range(0, shapes.Length)];
// value: a number from 0 up to 1: "one time in five".
bool rare = Random.value < 0.2f;
GameObject go = GameObject.Spawn(shape, place);
if (rare) go.SetColor(Color.yellow);
}
}
}
UI
static class UI
The game UI (UiCanvas screens): react to buttons and toggles, set text, values and visibility by object name (use unique names).
| Member | Description | Example |
|---|---|---|
static bool Clicked(string action) | True on the frame a button with this action was clicked. | if (UI.Clicked("play")) Scene.Load("Level1"); |
static bool Toggled(string action) | True on the frame a toggle with this action was clicked. | if (UI.Toggled("mute")) Audio.StopAll(); |
static bool Submitted(string action) | True on the frame Enter was pressed in a text input with this action. | if (UI.Submitted("name")) PlayerPrefs.SetString("playerName", UI.GetText("NameInput")); |
static bool Selected(string action) | True on the frame a choice was picked in a dropdown with this action (read its GetValue for the index). | if (UI.Selected("quality")) Debug.Log("quality " + (int)UI.GetValue("QualityDropdown")); |
static string GetText(string name) | A label's text. | if (UI.Submitted("name")) PlayerPrefs.SetString("playerName", UI.GetText("NameInput")); |
static void SetText(string name, string text) | Sets a label's text (the label stops following its localization key). | UI.SetText("Score", "Score " + score); |
static float GetValue(string name) | A progress bar's or slider's value. | if (UI.Selected("quality")) Debug.Log("quality " + (int)UI.GetValue("QualityDropdown")); |
static void SetValue(string name, float value) | Sets a slider or progress bar value. | UI.SetValue("HealthBar", health); |
static bool GetChecked(string name) | A toggle's state. | if (Input.GetKeyDown("M")) UI.SetChecked("MuteToggle", !UI.GetChecked("MuteToggle")); |
static void SetChecked(string name, bool on) | Sets a checkbox or toggle. | if (Input.GetKeyDown("M")) UI.SetChecked("MuteToggle", !UI.GetChecked("MuteToggle")); |
static void SetVisible(string name, bool visible) | Shows or hides a UI object and everything under it. | UI.SetVisible("LowHealthWarning", health < 0.25f); |
static bool Exists(string name) | True when a UI element with that name exists. | if (UI.Exists("EnemyDot")) UI.Clone("EnemyDot", "EnemyDot2"); |
static void Clone(string source, string newName) | Makes a copy of a UI object (and everything under it) next to the original, named newName: a dot per enemy on a minimap, a row per item in a list. Build one template object in the editor and clone it. The copy appears on the next frame (check UI.Exists(newName) before moving or colouring it) and starts as the original is now. | if (UI.Exists("EnemyDot")) UI.Clone("EnemyDot", "EnemyDot2"); |
static void Destroy(string name) | Removes a UI object and everything under it (for objects made with Clone, or ones the game is done with). | if (at.y < 0f) UI.Destroy("EnemyDot2"); |
static Vector3 FromScreen(Vector3 screen) | A game-view pixel (as Camera.WorldToScreen and Input.mousePosition give it: y up) as a position in the first UI canvas's units measured from its top left corner (x right, y down): give it to SetPosition on an object anchored TopLeft, so a label follows a world point: var c = UI.FromScreen(Camera.WorldToScreen(enemy.position)); UI.SetPosition("Tag", c.x, c.y); | Vector3 onCanvas = UI.FromScreen(Camera.WorldToScreen(enemy.transform.position)); |
static Vector3 GetPosition(string name) | Where a UI object sits: its offset from its anchor, in canvas units (x right, y down), as in the Rect component. | Vector3 at = UI.GetPosition("EnemyDot"); |
static void SetPosition(string name, float x, float y) | Moves a UI object: its offset from its anchor in canvas units (x right, y down). With anchor Center, (0, 0) is the middle of the parent; with TopRight, (-20, 20) is 20 units in from the top right corner. This is how a minimap dot, a health bar over an enemy or a floating label is moved every frame. | UI.SetPosition("EnemyDot", onCanvas.x, onCanvas.y); |
static Vector3 GetSize(string name) | A UI object's width and height in canvas units. | Vector3 size = UI.GetSize("EnemyDot"); |
static void SetSize(string name, float width, float height) | Resizes a UI object (canvas units). | UI.SetSize("EnemyDot", size.x, size.x); |
static float GetRotation(string name) | A UI object's turn in degrees (counter-clockwise). | UI.SetRotation("Needle", UI.GetRotation("Needle") + 90f * deltaTime); |
static void SetRotation(string name, float degrees) | Turns a UI object and everything under it about its middle, in degrees counter-clockwise: a compass needle or a player arrow on a minimap, a whole rotating panel. | UI.SetRotation("Needle", UI.GetRotation("Needle") + 90f * deltaTime); |
static void SetRotationPivot(string name, float x, float y) | Sets the point a UI object turns about, as fractions of its rect: (0.5, 0.5) is the middle (the default), (0, 0) the top-left corner, (0.5, 1) the middle of the bottom edge (a clock hand, a door). | UI.SetRotationPivot("Needle", 0.5f, 1f); |
static void Create(string kind, string name, string parent, float x, float y, float w, float h, string text = "") | Makes a new UI object from nothing. kind is "panel", "label" (text), "image" (text is the picture path) or "button"; parent is the name of a UI object or canvas to put it in (empty = the first canvas); x, y, w, h are in canvas units from the top-left. It exists from the next frame, so give it its looks with UI.SetColor and the other setters then. | UI.Create("panel", "Toast", "Hud", 0f, 40f, 300f, 60f); |
static void SetColor(string name, float r, float g, float b, float a = 1f) | Colours a UI object: a label's text colour, a picture's tint, else a panel's colour (r, g, b, a all 0..1). | UI.SetColor("Toast", 0f, 0f, 0f, 0.6f); |
static void SetColor(string name, Color c) | Sets a UI object's colour from a Color. | UI.SetColor("Toast", 0f, 0f, 0f, 0.6f); |
static void SetImage(string name, string path) | Changes the picture of a UI image (a project path such as "Textures/arrow.png"). | UI.SetImage("Portrait", "Textures/hero.png"); |
static void SetAnchor(string name, string anchor) | Changes where a UI object is pinned in its parent: TopLeft, Top, TopRight, Left, Center, Right, BottomLeft, Bottom, BottomRight, StretchAll ... | UI.SetAnchor("Toast", "Top"); |
Example (UI.cs)
// UI: the game's screens: reacting to buttons, changing text, bars, pictures and layout by object name.
public class UIExample : Behaviour
{
public GameObject enemy;
int score;
float health = 1f;
public override void Start()
{
// Create: a new UI object from nothing: kind "panel", "label", "image" or "button"; then its name, its parent,
// x, y, width, height and its text (a picture path for an image).
UI.Create("panel", "Toast", "Hud", 0f, 40f, 300f, 60f);
UI.Create("label", "ToastText", "Toast", 10f, 10f, 280f, 40f, "Welcome");
// SetAnchor: where the object is pinned in its parent (TopLeft, Top, TopRight, Left, Center, Right, Bottom...).
UI.SetAnchor("Toast", "Top");
// SetColor: a label's text colour, a picture's tint or a panel's colour (four numbers 0..1, or a Color).
UI.SetColor("Toast", 0f, 0f, 0f, 0.6f);
UI.SetColor("ToastText", Color.yellow);
// SetImage: changes the picture of a UI image.
UI.SetImage("Portrait", "Textures/hero.png");
// Exists: is there a UI object with this name? Clone: a copy (with everything under it) under a new name.
if (UI.Exists("EnemyDot")) UI.Clone("EnemyDot", "EnemyDot2");
}
public override void Update(float deltaTime)
{
// Clicked: true on the frame a button with this action was clicked.
if (UI.Clicked("play")) Scene.Load("Level1");
// Toggled: true on the frame a toggle was clicked; GetChecked reads its state, SetChecked sets it.
if (UI.Toggled("mute")) Audio.StopAll();
if (Input.GetKeyDown("M")) UI.SetChecked("MuteToggle", !UI.GetChecked("MuteToggle"));
// Submitted: true on the frame Enter was pressed in a text input; GetText reads what was typed.
if (UI.Submitted("name")) PlayerPrefs.SetString("playerName", UI.GetText("NameInput"));
// Selected: true on the frame a dropdown choice was picked; GetValue gives its index.
if (UI.Selected("quality")) Debug.Log("quality " + (int)UI.GetValue("QualityDropdown"));
// SetText: a label's text. SetValue: a slider or progress bar.
UI.SetText("Score", "Score " + score);
UI.SetValue("HealthBar", health);
// SetVisible: show or hide an object and everything under it.
UI.SetVisible("LowHealthWarning", health < 0.25f);
// A marker that follows an enemy: FromScreen turns a game-view pixel into a canvas position.
if (enemy != null)
{
Vector3 onCanvas = UI.FromScreen(Camera.WorldToScreen(enemy.transform.position));
// SetPosition: the offset from the anchor in canvas units (x right, y down). GetPosition reads it.
UI.SetPosition("EnemyDot", onCanvas.x, onCanvas.y);
Vector3 at = UI.GetPosition("EnemyDot");
// GetSize, SetSize: width and height in canvas units (the dot grows when the enemy is near).
Vector3 size = UI.GetSize("EnemyDot");
UI.SetSize("EnemyDot", size.x, size.x);
if (at.y < 0f) UI.Destroy("EnemyDot2"); // Destroy: removes a UI object and everything under it
}
// A compass needle: SetRotationPivot sets the point it turns about (fractions of its rect: 0.5, 1 is the middle
// of its foot), SetRotation turns it in degrees counter-clockwise, GetRotation reads the turn.
UI.SetRotationPivot("Needle", 0.5f, 1f);
UI.SetRotation("Needle", UI.GetRotation("Needle") + 90f * deltaTime);
}
}
Camera
static class Camera
The camera the game view looks through: where a world point lands on the screen (labels and health bars that follow an object, minimap maths, off-screen arrows). Screen positions use the same convention as Input.mousePosition: pixels of the game view, x to the right, y UP from the bottom edge.
| Member | Description | Example |
|---|---|---|
static void Focus(GameObject target, float seconds = 3f, float orbitDegrees = 0f, float distance = 4f, float height = 1.5f) | A cutscene shot: the camera eases to distance metres from target at height above it, looks at it, and circles it by orbitDegrees over seconds. The follow camera stands aside while the shot runs and eases back to the player after it, so nothing fights over the camera. focusing is true meanwhile. | if (Input.GetKeyDown("B")) Camera.Focus(boss, 4f, 90f, 6f, 2f); |
static void Release() | Ends a Focus shot early; the camera eases back to following. | if (Camera.focusing && Input.GetKeyDown("Space")) Camera.Release(); |
static void Shake(float strength = 0.3f, float seconds = 0.4f) | Shakes the view (an explosion, a hit, a landing): strength metres at first, dying away over seconds. Only the picture shakes; the camera object stays where it is. | if (Input.GetKeyDown("X")) Camera.Shake(0.5f, 0.6f); |
static bool focusing | True while a Focus shot is running. | if (Camera.focusing && Input.GetKeyDown("Space")) Camera.Release(); |
static Vector3 position | Where the camera is (3D). | Vector3 onScreen = Camera.WorldToScreen(transform.position + Vector3.up * 2f); |
static float fieldOfView | The camera's vertical field of view in degrees (3D; 0 for an orthographic or 2D camera). | Debug.Log("boss is " + far + " m from a " + Camera.fieldOfView + " degree camera"); |
static Vector3 WorldToScreen(Vector3 p) | The screen point of a world point: x, y in game-view pixels (y up) and z the distance in front of the camera (zero or less means it is behind the camera). In a 2D game z is 0 and x, y follow the 2D camera. | Vector3 onScreen = Camera.WorldToScreen(transform.position + Vector3.up * 2f); |
static Ray ScreenPointToRay(Vector3 screen) | The ray from the camera through a screen point (game-view pixels, y up, as WorldToScreen and Input.mousePosition give them): pass it to Physics.Raycast to find what the pointer is on. In a 2D game the ray starts in front of the scene and points into it. | Ray ray = Camera.ScreenPointToRay(Input.mousePosition); |
static Vector3 WorldToViewport(Vector3 p) | The same as WorldToScreen, as 0..1 of the game view (x right, y up). | Vector3 view = Camera.WorldToViewport(boss.transform.position); |
static bool OnScreen(Vector3 p) | True when the world point is in front of the camera and inside the game view. | UI.SetVisible("NameTag", Camera.OnScreen(transform.position)); |
Example (Camera.cs)
// Camera: where the world lands on the screen, cutscene shots, and shaking the view.
public class CameraExample : Behaviour
{
public GameObject boss;
public override void Update(float deltaTime)
{
// WorldToScreen: a world point in game-view pixels (y up); z is the distance in front of the camera.
Vector3 onScreen = Camera.WorldToScreen(transform.position + Vector3.up * 2f);
// OnScreen: is the point in front of the camera and inside the view?
UI.SetVisible("NameTag", Camera.OnScreen(transform.position));
Vector3 canvas = UI.FromScreen(onScreen);
UI.SetPosition("NameTag", canvas.x, canvas.y);
// WorldToViewport: the same as 0..1 of the view: an arrow at the edge for something off to the side.
Vector3 view = Camera.WorldToViewport(boss.transform.position);
UI.SetVisible("BossArrowLeft", view.x < 0f);
UI.SetVisible("BossArrowRight", view.x > 1f);
// ScreenPointToRay: the ray from the camera through a screen point: what is under the pointer?
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, 100f)) Debug.Log("clicked " + hit.gameObject.name);
}
// position and fieldOfView: where the camera is, and how wide it sees (degrees; 0 for a 2D camera).
float far = Vector3.Distance(Camera.position, boss.transform.position);
Debug.Log("boss is " + far + " m from a " + Camera.fieldOfView + " degree camera");
// Focus: a cutscene shot: ease to 6 m from the boss, 2 m up, look at it for 4 seconds while circling 90 degrees.
if (Input.GetKeyDown("B")) Camera.Focus(boss, 4f, 90f, 6f, 2f);
// focusing: true while a Focus shot runs. Release: end it early.
if (Camera.focusing && Input.GetKeyDown("Space")) Camera.Release();
// Shake: shake the view: 0.5 m at first, dying away over 0.6 seconds (an explosion).
if (Input.GetKeyDown("X")) Camera.Shake(0.5f, 0.6f);
}
}
Input
static class Input
Keyboard, pointer and gamepad input.
| Member | Description | Example |
|---|---|---|
static int touchCount | How many fingers are on the game view. | for (int i = 0; i < Input.touchCount; i++) |
static Vector3 GetTouch(int index) | A finger's place on the game view: x 0..1 left to right, y 0..1 top to bottom (z is 0). | Vector3 finger = Input.GetTouch(i); |
static bool GetAction(string name) | True while an input action is active (Project Settings > Input: "Jump", "Fire", "Submit", "Cancel", or your own). Keys, mouse and gamepads all count, as the player bound them. | if (Input.GetAction("Fire")) Debug.Log("firing"); |
static bool GetActionDown(string name) | True on the frame the action became active. | if (Input.GetActionDown("Jump")) Debug.Log("jump"); |
static bool GetActionUp(string name) | True on the frame the action stopped. | if (Input.GetActionUp("Fire")) Debug.Log("stopped firing"); |
static float GetAxis(string name) | An axis action's value, -1..1 ("Horizontal", "Vertical"): keys give -1/0/1, sticks anything between (past a small dead zone). | Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0f, -Input.GetAxis("Vertical")); |
static bool GetKey(string key) | True while the key is held. Names: "W", "A", "1", "Space", "Up", "Down", "Left", "Right", "Enter", "Escape", "Tab", "Shift", "Ctrl", "Alt" (LeftShift, Return and the like work too). For sprint, prefer Input.GetAction("Sprint"): it is bound to Shift and a gamepad shoulder button. | bool running = Input.GetKey("Shift"); |
static bool GetKeyDown(string key) | True on the frame a key went down. | if (Input.GetKeyDown("R")) Debug.Log("reload"); |
static bool GetKeyUp(string key) | True on the frame a key went up. | if (Input.GetKeyUp("Tab")) Debug.Log("closed the map"); |
static string GetAnyKeyDown() | The key that went down this frame, by the name GetKey takes ("J", "Space", "Shift"), or null when none did: what a "press a key" button of an options menu waits for. | string pressed = Input.GetAnyKeyDown(); |
static void Rebind(string action, string key, int slot = 0) | Binds an input action to a key from now on: its binding number slot (0, the first, is the key Project Settings > Input gives it) becomes key, or the key is added when the action has no such binding. It lasts while the game runs (the editor's play ends with the project's bindings again): keep the player's choice in PlayerPrefs and bind it again at the start. Input.Rebind("Jump", "J"). | if (waitingForKey && pressed != null) { Input.Rebind("Jump", pressed); PlayerPrefs.SetString("jump key", pr... |
static void RebindAxis(string action, string negative, string positive, int slot = 0) | Binds an axis action ("Horizontal", "Vertical") to a pair of keys: negative gives -1 and positive +1. Input.RebindAxis("Horizontal", "J", "L"). Lasts as Rebind does. | if (Input.GetKeyDown("F2")) Input.RebindAxis("Horizontal", "J", "L"); |
static string GetBinding(string action, int slot = 0) | What an action is bound to now, as a player reads it: "Space", "A / D", "Pad South", "Mouse Left"; "" when it has no binding number slot. For the labels of an options menu. | Debug.Log("Jump is " + Input.GetBinding("Jump") + ", walking is " + Input.GetBinding("Horizontal")); |
static void ResetBindings() | Puts every action back to the project's own bindings (Project Settings > Input). | if (Input.GetKeyDown("F3")) { Input.ResetBindings(); PlayerPrefs.DeleteKey("jump key"); } |
static bool GetMouseButton(int button) | 0 = left button, 1 = right button, 2 = middle button. | if (Input.GetMouseButton(1)) Debug.Log("aiming"); |
static bool GetMouseButtonDown(int button) | True on the frame a mouse button went down (0 = left, 1 = right, 2 = middle). | if (Input.GetMouseButtonDown(0)) Debug.Log("pressed at " + Input.mousePosition); |
static bool GetMouseButtonUp(int button) | True on the frame a mouse button went up. | if (Input.GetMouseButtonUp(0)) Debug.Log("released"); |
static Vector3 mousePosition | Where the mouse is over the game view, in pixels with the origin at the bottom left: z is 0. Screen.width and Screen.height are the view's size. | if (Input.GetMouseButtonDown(0)) Debug.Log("pressed at " + Input.mousePosition); |
static Vector3 mousePositionNormalized | Where the mouse is over the game view as 0..1: x left to right, y top to bottom (the same units as touches). | Vector3 n = Input.mousePositionNormalized; |
static Vector3 mouseDelta | How far the mouse moved since the last frame, in pixels (y up). Works while the cursor is locked. | transform.Rotate(new Vector3(0f, -Input.mouseDelta.x * 0.2f, 0f)); |
static bool mouseOverGame | True while the mouse is over the game view (false when it is over an editor panel). | if (Input.mouseOverGame && n.x > 0.9f) Debug.Log("pointer near the right edge"); |
static float mouseScrollDelta | Wheel notches this frame: forward (away from you) is positive. | speed = Mathf.Clamp(speed + Input.mouseScrollDelta, 1f, 20f); |
static int mouseClickCount | How many quick presses of the left button in a row ended on this frame (1 single, 2 double, 3 triple); meaningful on the frame GetMouseButtonDown is true. | if (Input.GetMouseButtonDoubleClick(0)) Debug.Log("double click, count " + Input.mouseClickCount); |
static bool GetMouseButtonDoubleClick(int button) | True on the frame of a double click (or more) of a mouse button. | if (Input.GetMouseButtonDoubleClick(0)) Debug.Log("double click, count " + Input.mouseClickCount); |
static Vector3 mouseWorldPosition | The pointer in the world: in a 2D game the point under it (z = 0); in a 3D game where its ray meets the ground plane y = 0 (zero when the ray does not reach it). | Vector3 aim = Input.mouseWorldPosition; |
static bool MouseRay(out Vector3 origin, out Vector3 direction) | The pointer's ray into a 3D game: its origin and direction. False in a 2D game or off the view. | if (Input.MouseRay(out Vector3 origin, out Vector3 direction)) Gizmos.DrawRay(origin, direction); |
static bool MouseRaycast(out RaycastHit hit, float maxDistance = float.MaxValue) | The nearest object under the pointer in a 3D game (see Physics.Raycast). | if (Input.MouseRaycast(out RaycastHit hit, 50f)) aim = hit.point; |
static float Axis(string negative, string positive) | -1, 0 or 1 from a pair of keys, e.g. Axis("A", "D"). | float lean = Input.Axis("Q", "E"); |
Example (Input.cs)
// Input: keys, the mouse, touches, gamepads and the named actions of Project Settings > Input.
public class InputExample : Behaviour
{
public float speed = 5f;
public override void Update(float deltaTime)
{
// GetAxis: -1..1 from a named axis ("Horizontal", "Vertical"): keys, a stick or the touch stick.
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0f, -Input.GetAxis("Vertical"));
// Axis: -1, 0 or 1 from any pair of keys.
float lean = Input.Axis("Q", "E");
transform.position += move * speed * deltaTime;
transform.Rotate(new Vector3(0f, 0f, -lean * 45f * deltaTime));
// GetAction, GetActionDown, GetActionUp: a named action (keyboard, gamepad and touch buttons at once).
if (Input.GetActionDown("Jump")) Debug.Log("jump");
if (Input.GetAction("Fire")) Debug.Log("firing");
if (Input.GetActionUp("Fire")) Debug.Log("stopped firing");
// GetKey, GetKeyDown, GetKeyUp: one key by name ("W", "Space", "Left", "Enter", "Escape", "F1"...).
bool running = Input.GetKey("Shift");
if (Input.GetKeyDown("R")) Debug.Log("reload");
if (Input.GetKeyUp("Tab")) Debug.Log("closed the map");
if (running) transform.position += move * speed * deltaTime;
// GetMouseButton, GetMouseButtonDown, GetMouseButtonUp: 0 left, 1 right, 2 middle.
if (Input.GetMouseButtonDown(0)) Debug.Log("pressed at " + Input.mousePosition); // pixels, origin bottom left
if (Input.GetMouseButton(1)) Debug.Log("aiming");
if (Input.GetMouseButtonUp(0)) Debug.Log("released");
// GetMouseButtonDoubleClick and mouseClickCount: double (or triple) clicks.
if (Input.GetMouseButtonDoubleClick(0)) Debug.Log("double click, count " + Input.mouseClickCount);
// mousePositionNormalized: the pointer as 0..1 (x left to right, y top to bottom), like touches.
Vector3 n = Input.mousePositionNormalized;
// mouseOverGame: false while the pointer is over an editor panel instead of the game.
if (Input.mouseOverGame && n.x > 0.9f) Debug.Log("pointer near the right edge");
// mouseDelta: pixels moved since the last frame (works while the cursor is locked): first-person look.
transform.Rotate(new Vector3(0f, -Input.mouseDelta.x * 0.2f, 0f));
// mouseScrollDelta: wheel notches this frame (forward is positive): zoom.
speed = Mathf.Clamp(speed + Input.mouseScrollDelta, 1f, 20f);
// mouseWorldPosition: the pointer in the world (2D: the point under it; 3D: where its ray meets the ground).
Vector3 aim = Input.mouseWorldPosition;
// MouseRay: the pointer's ray into a 3D game. MouseRaycast: the nearest object under the pointer.
if (Input.MouseRay(out Vector3 origin, out Vector3 direction)) Gizmos.DrawRay(origin, direction);
if (Input.MouseRaycast(out RaycastHit hit, 50f)) aim = hit.point;
transform.LookAt(aim);
// touchCount and GetTouch: fingers on the view; each as 0..1 (x left to right, y top to bottom).
for (int i = 0; i < Input.touchCount; i++)
{
Vector3 finger = Input.GetTouch(i);
if (finger.x > 0.5f) Debug.Log("finger " + i + " on the right half");
}
// Controls the player chooses (an options menu):
// GetBinding: what an action is bound to, as the player reads it ("Space", "A / D", "Pad South").
Debug.Log("Jump is " + Input.GetBinding("Jump") + ", walking is " + Input.GetBinding("Horizontal"));
// GetAnyKeyDown: the key that went down this frame, or null: "press a key" for a binding.
string pressed = Input.GetAnyKeyDown();
// Rebind: an action's first binding (or binding number `slot`) becomes that key, while the game runs.
if (waitingForKey && pressed != null) { Input.Rebind("Jump", pressed); PlayerPrefs.SetString("jump key", pressed); waitingForKey = false; }
// RebindAxis: an axis action on a pair of keys, the negative one first.
if (Input.GetKeyDown("F2")) Input.RebindAxis("Horizontal", "J", "L");
// ResetBindings: every action as Project Settings > Input has it again.
if (Input.GetKeyDown("F3")) { Input.ResetBindings(); PlayerPrefs.DeleteKey("jump key"); }
}
bool waitingForKey;
}
AssetRef
class AssetRef
A project asset a script field refers to: the field shows up in the Inspector as an object field (drag an asset onto it or browse). path is the asset's project path.
| Member | Description | Example |
|---|---|---|
string path | The asset's project path, for example "Audio/jump.wav". | Debug.Log("playing " + sound.name + " from " + sound.path); |
string name | The file name without its extension. | Debug.Log("playing " + sound.name + " from " + sound.path); |
override string ToString() | The asset's project path. | Debug.Log(sound.ToString()); |
static implicit operator string(AssetRef a) | An asset used where a path is wanted gives its path (null for a missing asset). | string path = pickupSound; |
Example (AssetRef.cs)
// AssetRef: a project file a script field points at; the field shows in the Inspector as a slot to drop the asset on.
public class AssetRefExample : Behaviour
{
// Every asset type derives from AssetRef: AudioClip, Texture, Sprite, Material, Mesh, Prefab, AnimationClip, TextAsset.
public AudioClip pickupSound;
public Prefab pickupEffect;
public override void OnTriggerEnter(GameObject other)
{
AssetRef sound = pickupSound;
// path: the asset's project path ("Audio/pickup.wav"). name: the file name without its extension ("pickup").
Debug.Log("playing " + sound.name + " from " + sound.path);
// ToString gives the path too.
Debug.Log(sound.ToString());
// An asset used where a path is wanted turns into its path by itself (null when the slot is empty).
string path = pickupSound;
if (path != null) Audio.Play(path);
Audio.Play(pickupSound);
GameObject.Instantiate(pickupEffect, transform.position);
}
}
AudioClip
class AudioClip : AssetRef { }
A sound file: a public AudioClip jump; field takes one from the Project window.
Example (AudioClip.cs)
// AudioClip: a sound file as a script field: drag a .wav, .ogg, .mp3 or .flac from the Project window onto it.
public class AudioClipExample : Behaviour
{
public AudioClip jump;
public AudioClip[] footsteps; // a list of clips works too
float nextStep;
public override void Update(float deltaTime)
{
// A clip goes straight into Audio.Play (it turns into its path).
if (Input.GetActionDown("Jump") && jump != null) Audio.Play(jump, 0.8f);
nextStep -= deltaTime;
if (nextStep <= 0f && footsteps.Length > 0 && Input.GetAxis("Vertical") != 0f)
{
AudioClip step = footsteps[Random.Range(0, footsteps.Length)];
Audio.PlayAt(step, transform.position, 0.5f, Random.Range(0.9f, 1.1f));
nextStep = 0.4f;
}
}
}
Texture
class Texture : AssetRef { }
A picture file.
Example (Texture.cs)
// Texture: a picture file as a script field: drag a .png or .jpg from the Project window onto it.
public class TextureExample : Behaviour
{
public Texture damaged;
public Texture[] skins;
public override void OnCollisionEnter(GameObject other)
{
// A texture goes wherever a picture path is wanted: here, the sprite or the material's picture of this object.
if (damaged != null) gameObject.Set("SpriteRenderer", "texture", damaged);
}
public void WearSkin(int k)
{
Texture skin = skins[k % skins.Length];
Debug.Log("wearing " + skin.name);
UI.SetImage("SkinPreview", skin);
}
}
Texture2D
class Texture2D : Texture { }
A picture file (the same as a Texture here).
Example (Texture2D.cs)
// Texture2D: a picture file (the same as a Texture here; the other common name).
public class Texture2DExample : Behaviour
{
public Texture2D icon;
public override void Start()
{
// Used like any Texture: it turns into its project path where one is wanted.
if (icon != null) UI.SetImage("ItemIcon", icon);
Texture2D[] none = new Texture2D[0];
Debug.Log("icon: " + (icon == null ? "none" : icon.path) + "; " + none.Length + " extra pictures");
}
}
Sprite
class Sprite : Texture { }
A picture file used as a 2D sprite.
Example (Sprite.cs)
// Sprite: a picture used as a 2D sprite, as a script field.
public class SpriteExample : Behaviour
{
public Sprite idle;
public Sprite hurt;
float flash;
public override void OnCollisionEnter(GameObject other)
{
flash = 0.2f;
// Change the picture the object's SpriteRenderer shows.
if (hurt != null) gameObject.Set("SpriteRenderer", "texture", hurt);
}
public override void Update(float deltaTime)
{
if (flash <= 0f) return;
flash -= deltaTime;
if (flash <= 0f && idle != null) gameObject.Set("SpriteRenderer", "texture", idle);
}
}
Material
class Material : AssetRef { }
A material asset (.mat).
Example (Material.cs)
// Material: a material asset (.mat) as a script field.
public class MaterialExample : Behaviour
{
public Material normal;
public Material frozen;
public void Freeze(bool on)
{
Material use = on ? frozen : normal;
// SetMaterial takes a project path; a Material turns into its path by itself.
if (use != null) gameObject.SetMaterial(use);
}
public override void Update(float deltaTime)
{
if (Input.GetKeyDown("F")) Freeze(true);
if (Input.GetKeyUp("F")) Freeze(false);
}
}
Mesh
class Mesh : AssetRef { }
A model file (.glb / .gltf).
Example (Mesh.cs)
// Mesh: a model file (.glb or .gltf) as a script field.
public class MeshExample : Behaviour
{
public Mesh rock;
public int count = 12;
public override void Start()
{
if (rock == null) return;
for (int i = 0; i < count; i++)
{
// GameObject.Spawn takes a Mesh field and a place.
GameObject go = GameObject.Spawn(rock, new Vector3(Random.Range(-20f, 20f), 0f, Random.Range(-20f, 20f)));
go.transform.rotation = new Vector3(0f, Random.Range(0f, 360f), 0f);
go.AddCollider();
}
Debug.Log("scattered " + count + " of " + rock.name);
}
}
Prefab
class Prefab : AssetRef { }
A saved object tree: GameObject.Instantiate(prefab, position) makes a copy.
Example (Prefab.cs)
// Prefab: a saved object tree as a script field; Instantiate makes copies of it.
public class PrefabExample : Behaviour
{
public Prefab bullet;
public float fireEvery = 0.2f;
float cooldown;
public override void Update(float deltaTime)
{
cooldown -= deltaTime;
if (bullet == null || cooldown > 0f || !Input.GetAction("Fire")) return;
cooldown = fireEvery;
// GameObject.Instantiate(prefab, position): a copy of the prefab with its root at the position.
GameObject shot = GameObject.Instantiate(bullet, transform.position + transform.forward);
shot.transform.rotation = transform.rotation;
shot.rigidbody.velocity = transform.forward * 30f;
}
}
AnimationClip
class AnimationClip : AssetRef { }
An animation clip asset (.anim).
Example (AnimationClip.cs)
// AnimationClip: an animation clip asset (.anim) as a script field.
public class AnimationClipExample : Behaviour
{
public AnimationClip open;
public AnimationClip close;
bool isOpen;
public override void OnMouseDown()
{
isOpen = !isOpen;
AnimationClip clip = isOpen ? open : close;
// The object's Animator plays the clip: set which one and start it.
if (clip != null && gameObject.animator != null)
{
gameObject.Set("Animator", "clip", clip);
gameObject.animator.Play();
}
}
}
TextAsset
class TextAsset : AssetRef { }
A text file (.txt, .json, .csv ...).
Example (TextAsset.cs)
// TextAsset: a text file (.txt, .json, .csv) as a script field.
public class TextAssetExample : Behaviour
{
public TextAsset waves; // a CSV of enemy waves, edited as a grid in the editor
public override void Start()
{
if (waves == null) return;
// A CSV text asset loads as a DataTable by its path.
DataTable table = DataTable.Load(waves);
foreach (string wave in table.rows)
Debug.Log(wave + ": " + table.GetInt(wave, "count") + " x " + table.Get(wave, "enemy"));
Debug.Log("read " + waves.name + " from " + waves.path);
}
}
Gizmos
static class Gizmos
Lines a script draws in the Scene view from its OnDrawGizmos (always) or OnDrawGizmosSelected (while its object is selected): a patrol route, a detection radius, a spawn area. They show in the editor and while playing, never in the game. Positions are in the world (transform.TransformPoint turns a point on the object into one).
| Member | Description | Example |
|---|---|---|
static Color color | The colour of what is drawn next (each script starts with white). | Gizmos.color = Color.yellow; |
static void DrawLine(Vector3 from, Vector3 to) | A line between two points. | Gizmos.DrawLine(transform.position, patrol[0]); |
static void DrawRay(Vector3 from, Vector3 direction) | A line from a point along a direction, as long as the direction. | Gizmos.DrawRay(transform.position, transform.forward * 2f); |
static void DrawLineStrip(Vector3[] points, bool looped) | Lines joining the points in order, and the last back to the first when looped. | Gizmos.DrawLineStrip(patrol, true); |
static void DrawWireDisc(Vector3 center, Vector3 normal, float radius) | A circle around normal (Vector3.up: flat on the ground). | Gizmos.DrawWireDisc(transform.position, Vector3.up, sight); |
static void DrawWireSphere(Vector3 center, float radius) | A sphere's outline: a circle around each axis. | Gizmos.DrawWireSphere(transform.position, sight * 0.5f); |
static void DrawSphere(Vector3 center, float radius) | The same outline as DrawWireSphere (solid shapes are drawn as outlines here). | Gizmos.DrawSphere(transform.position + transform.forward, 0.1f); |
static void DrawWireCube(Vector3 center, Vector3 size) | The edges of a box lined up with the world axes. | foreach (Vector3 p in patrol) Gizmos.DrawWireCube(p, Vector3.one * 0.3f); |
static void DrawCube(Vector3 center, Vector3 size) | The same edges as DrawWireCube (solid shapes are drawn as outlines here). | Gizmos.DrawCube(transform.position + Vector3.up * 2f, Vector3.one * 0.2f); |
Example (Gizmos.cs)
// Gizmos: lines a script draws in the Scene view to show what it does: routes, ranges, zones.
public class GizmosExample : Behaviour
{
public Vector3[] patrol = { new Vector3(0, 0, 0), new Vector3(5, 0, 0), new Vector3(5, 0, 5) };
public float sight = 8f;
public Vector3 zoneSize = new Vector3(4f, 2f, 4f);
// Drawn all the time in the Scene view.
public override void OnDrawGizmos()
{
// color: the colour of what is drawn next.
Gizmos.color = Color.yellow;
// DrawLineStrip: lines joining the points in order (true: and back to the first).
Gizmos.DrawLineStrip(patrol, true);
// DrawWireCube / DrawCube: the edges of a box lined up with the world axes.
foreach (Vector3 p in patrol) Gizmos.DrawWireCube(p, Vector3.one * 0.3f);
Gizmos.DrawCube(transform.position + Vector3.up * 2f, Vector3.one * 0.2f);
}
// Drawn only while this object is selected.
public override void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
// DrawWireDisc: a circle about a normal (Vector3.up: flat on the ground): how far it sees.
Gizmos.DrawWireDisc(transform.position, Vector3.up, sight);
// DrawWireSphere / DrawSphere: a sphere's outline: how far it hears.
Gizmos.DrawWireSphere(transform.position, sight * 0.5f);
Gizmos.DrawSphere(transform.position + transform.forward, 0.1f);
Gizmos.color = Color.cyan;
// DrawRay: a line from a point along a direction: which way it faces.
Gizmos.DrawRay(transform.position, transform.forward * 2f);
// DrawLine: a line between two points: to its first patrol point.
Gizmos.DrawLine(transform.position, patrol[0]);
Gizmos.DrawWireCube(transform.position, zoneSize);
}
}
Timeline
static class Timeline
Cutscenes: a Timeline component plays a .timeline file (camera shots, model animations, objects switched on and off, sounds, moves and script events laid out in time). Its event clips reach scripts through Events.On(name, ...).
| Member | Description | Example |
|---|---|---|
static void Play(GameObject director) | Plays the timeline of director (its Timeline component) from the start. | Timeline.Play(intro); |
static void Stop(GameObject director) | Stops it where it is (a camera shot it runs ends, and the camera eases back). | if (Input.GetKeyDown("Space")) Timeline.Stop(intro); |
static bool IsPlaying(GameObject director) | True while it plays. | if (Timeline.IsPlaying(intro)) |
static float TimeOf(GameObject director) | How far it is, in seconds (-1 when it is not playing). | UI.SetText("SkipHint", "Space to skip (" + Mathf.RoundToInt(Timeline.TimeOf(intro)) + " s)"); |
Example (Timeline.cs)
// Timeline: playing a cutscene (a Timeline component's .timeline file) from a script.
public class TimelineExample : Behaviour
{
public GameObject intro; // the object with the Timeline component
bool played;
public override void OnTriggerEnter(GameObject other)
{
if (played || other != GameObject.FindPlayer()) return;
played = true;
// Play: plays the object's timeline from the start.
Timeline.Play(intro);
}
public override void Update(float deltaTime)
{
// IsPlaying: true while it plays. TimeOf: how far it is in seconds (-1 when it is not playing).
if (Timeline.IsPlaying(intro))
{
UI.SetText("SkipHint", "Space to skip (" + Mathf.RoundToInt(Timeline.TimeOf(intro)) + " s)");
// Stop: stops it where it is; a camera shot it runs ends and the camera eases back.
if (Input.GetKeyDown("Space")) Timeline.Stop(intro);
}
UI.SetVisible("SkipHint", Timeline.IsPlaying(intro));
}
}
HeaderAttribute
class HeaderAttribute : Attribute
Shows a heading above this field in the Inspector.
| Member | Description | Example |
|---|---|---|
readonly string header | The heading's text. | Debug.Log("fields under '" + h.header + "': speed " + speed + ", jump " + jumpHeight + "; damage " + damage); |
HeaderAttribute(string header) | A heading with this text. | [Header("Movement")] |
Example (HeaderAttribute.cs)
// HeaderAttribute: a heading above a group of fields in the Inspector.
public class HeaderAttributeExample : Behaviour
{
[Header("Movement")]
public float speed = 5f;
public float jumpHeight = 2f;
[Header("Combat")]
public int damage = 10;
public override void Start()
{
// header: the heading's text (the editor reads it; a script rarely needs to).
HeaderAttribute h = new HeaderAttribute("Movement");
Debug.Log("fields under '" + h.header + "': speed " + speed + ", jump " + jumpHeight + "; damage " + damage);
}
}
TooltipAttribute
class TooltipAttribute : Attribute
What the Inspector shows under the pointer over this field.
| Member | Description | Example |
|---|---|---|
readonly string tooltip | The tooltip's text. | Debug.Log("speed " + speed + " (" + t.tooltip + "), mercy " + mercyTime); |
TooltipAttribute(string tooltip) | A tooltip with this text. | [Tooltip("Metres a second on flat ground")] |
Example (TooltipAttribute.cs)
// TooltipAttribute: the text the Inspector shows when the pointer rests on a field.
public class TooltipAttributeExample : Behaviour
{
[Tooltip("Metres a second on flat ground")]
public float speed = 5f;
[Tooltip("Seconds the player cannot be hurt again after a hit")]
public float mercyTime = 1.5f;
public override void Start()
{
// tooltip: the text (the editor reads it).
TooltipAttribute t = new TooltipAttribute("Metres a second on flat ground");
Debug.Log("speed " + speed + " (" + t.tooltip + "), mercy " + mercyTime);
}
}
SpaceAttribute
class SpaceAttribute : Attribute
Leaves a gap above this field in the Inspector.
| Member | Description | Example |
|---|---|---|
readonly float height | How tall the gap is, in pixels. | Debug.Log(playerName + ": speed " + speed + ", lives " + lives + " (gap " + gap.height + " px)"); |
SpaceAttribute(float height = 8f) | A gap of this height. | [Space] |
Example (SpaceAttribute.cs)
// SpaceAttribute: a gap above a field in the Inspector, to set groups apart.
public class SpaceAttributeExample : Behaviour
{
public float speed = 5f;
[Space] // the usual gap, 8 pixels
public int lives = 3;
[Space(24f)] // a taller gap
public string playerName = "Ana";
public override void Start()
{
// height: how tall the gap is, in pixels.
SpaceAttribute gap = new SpaceAttribute(24f);
Debug.Log(playerName + ": speed " + speed + ", lives " + lives + " (gap " + gap.height + " px)");
}
}
RangeAttribute
class RangeAttribute : Attribute
Shows this number as a slider between two values in the Inspector.
| Member | Description | Example |
|---|---|---|
readonly float min | The slider's lowest value. | Debug.Log("volume " + volume + " of " + r.min + ".." + r.max + ", difficulty " + difficulty); |
readonly float max | The slider's highest value. | Debug.Log("volume " + volume + " of " + r.min + ".." + r.max + ", difficulty " + difficulty); |
RangeAttribute(float min, float max) | A slider from min to max. | [Range(0f, 1f)] |
Example (RangeAttribute.cs)
// RangeAttribute: shows a number as a slider between two values in the Inspector.
public class RangeAttributeExample : Behaviour
{
[Range(0f, 1f)]
public float volume = 0.8f;
[Range(1, 10)]
public int difficulty = 3;
public override void Start()
{
// min, max: the slider's ends.
RangeAttribute r = new RangeAttribute(0f, 1f);
Debug.Log("volume " + volume + " of " + r.min + ".." + r.max + ", difficulty " + difficulty);
}
}
HideInInspectorAttribute
class HideInInspectorAttribute : Attribute { }
Keeps this field out of the Inspector; it is still saved.
Example (HideInInspectorAttribute.cs)
// HideInInspectorAttribute: keeps a public field out of the Inspector; other scripts still see it and it is still saved.
public class HideInInspectorAttributeExample : Behaviour
{
public float speed = 5f; // shown
[HideInInspector]
public float currentSpeed; // public for other scripts to read, but not for editing by hand
public override void Update(float deltaTime)
{
currentSpeed = Mathf.Lerp(currentSpeed, speed * Input.GetAxis("Vertical"), 5f * deltaTime);
// The attribute has no values of its own.
HideInInspectorAttribute marker = new HideInInspectorAttribute();
if (marker != null) transform.position += transform.forward * currentSpeed * deltaTime;
}
}
MinAttribute
class MinAttribute : Attribute
The Inspector does not let this number go below a value: one typed lower becomes it.
| Member | Description | Example |
|---|---|---|
readonly float min | The lowest value. | Debug.Log("up to " + maxEnemies + " enemies (at least " + m.min + "), respawn after " + respawnDelay + " s"); |
MinAttribute(float min) | Nothing below min. | [Min(0f)] |
Example (MinAttribute.cs)
// MinAttribute: the Inspector will not let a number go below a value.
public class MinAttributeExample : Behaviour
{
[Min(0f)]
public float respawnDelay = 2f; // never negative
[Min(1f)]
public int maxEnemies = 5; // at least one
public override void Start()
{
// min: the lowest value allowed.
MinAttribute m = new MinAttribute(1f);
Debug.Log("up to " + maxEnemies + " enemies (at least " + m.min + "), respawn after " + respawnDelay + " s");
}
}
TextAreaAttribute
class TextAreaAttribute : Attribute
Shows this string as a box of several lines in the Inspector.
| Member | Description | Example |
|---|---|---|
readonly int minLines, maxLines | The fewest and the most lines the box shows. | Debug.Log(dialogue + " / " + description + " (boxes of " + box.minLines + "-" + box.maxLines + " and " + us... |
TextAreaAttribute() | A box of 3 to 8 lines. | [TextArea] |
TextAreaAttribute(int minLines, int maxLines) | A box of minLines to maxLines lines. | [TextArea] |
Example (TextAreaAttribute.cs)
// TextAreaAttribute: shows a string as a box of several lines in the Inspector.
public class TextAreaAttributeExample : Behaviour
{
[TextArea] // 3 to 8 lines
public string description = "A rusty key.\nIt opens the cellar door.";
[TextArea(2, 5)] // 2 to 5 lines
public string dialogue = "Who goes there?";
public override void OnMouseDown()
{
// minLines, maxLines: the fewest and the most lines the box shows.
TextAreaAttribute box = new TextAreaAttribute(2, 5);
TextAreaAttribute usual = new TextAreaAttribute();
Debug.Log(dialogue + " / " + description + " (boxes of " + box.minLines + "-" + box.maxLines + " and " + usual.minLines + "-" + usual.maxLines + " lines)");
}
}
MultilineAttribute
class MultilineAttribute : Attribute
Shows this string as a box of several lines in the Inspector (as TextArea).
| Member | Description | Example |
|---|---|---|
readonly int lines | How many lines. | Debug.Log("the letter's box shows " + m.lines + " lines"); |
MultilineAttribute(int lines = 3) | A box of lines lines. | [Multiline] |
Example (MultilineAttribute.cs)
// MultilineAttribute: shows a string as a box of a set number of lines in the Inspector.
public class MultilineAttributeExample : Behaviour
{
[Multiline] // 3 lines
public string signText = "Beware of the dog";
[Multiline(6)] // 6 lines
public string letter = "Dear traveller,\nthe bridge is out.";
public override void OnMouseDown()
{
// lines: how many lines the box shows.
MultilineAttribute m = new MultilineAttribute(6);
UI.SetText("Reader", signText + "\n\n" + letter);
Debug.Log("the letter's box shows " + m.lines + " lines");
}
}
MenuItemAttribute
class MenuItemAttribute : Attribute
Puts a static method in the editor's Tools window, under Your Scripts ("Tools/Line Up Crates"): choosing it runs the method in the editor on the scene as it is (not in the game), and what it changes is one undo step.
| Member | Description | Example |
|---|---|---|
readonly string path | Where it shows, for example "Tools/Line Up Crates". | Debug.Log("the editor has a menu item at " + item.path); |
MenuItemAttribute(string path) | A menu item at this path. | [MenuItem("Tools/Line Up Crates")] |
Example (MenuItemAttribute.cs)
// MenuItemAttribute: puts a static method in the editor's Tools window (Your Scripts); choosing it runs the method on the open scene.
public class MenuItemAttributeExample : Behaviour
{
// Tools window > Your Scripts > Line Up Crates: runs in the editor (not in the game); the whole run is one undo step.
[MenuItem("Tools/Line Up Crates")]
static void LineUpCrates()
{
int n = 0;
foreach (GameObject crate in GameObject.FindWithTag("Crate"))
crate.transform.position = new Vector3(n++ * 1.5f, 0.5f, 0f);
Debug.Log("lined up " + n + " crates");
}
public override void Start()
{
// path: where the item shows in the menu.
MenuItemAttribute item = new MenuItemAttribute("Tools/Line Up Crates");
Debug.Log("the editor has a menu item at " + item.path);
}
}
ContextMenuAttribute
class ContextMenuAttribute : Attribute
Puts a method of a script on its Script component in the Inspector, as a button: pressing it runs the method on that object's script in the editor (not in the game), and what it changes, the script's fields included, is one undo step.
| Member | Description | Example |
|---|---|---|
readonly string name | The button's label. | Debug.Log("this script has an Inspector button: " + button.name); |
ContextMenuAttribute(string name) | A button with this label. | [ContextMenu("Lay Out Ring")] |
Example (ContextMenuAttribute.cs)
// ContextMenuAttribute: a button on the script's component in the Inspector that runs one of its methods in the editor.
public class ContextMenuAttributeExample : Behaviour
{
public int ringCount = 8;
public float radius = 4f;
// Shows as a button "Lay Out Ring" on this script in the Inspector.
[ContextMenu("Lay Out Ring")]
void LayOutRing()
{
for (int i = 0; i < ringCount; i++)
{
float a = i * Mathf.PI * 2f / ringCount;
GameObject.Spawn("Cube", transform.position + new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a)) * radius);
}
}
public override void Start()
{
// name: the button's label.
ContextMenuAttribute button = new ContextMenuAttribute("Lay Out Ring");
Debug.Log("this script has an Inspector button: " + button.name);
}
}
Selection
static class Selection
What is selected in the editor, for menu items and Inspector buttons (nothing in a game).
| Member | Description | Example |
|---|---|---|
static GameObject activeGameObject | The selected object (the one clicked last), or null. | GameObject last = Selection.activeGameObject; |
static GameObject[] gameObjects | Every selected object. | foreach (GameObject go in Selection.gameObjects) |
Example (Selection.cs)
// Selection: what is selected in the editor, for menu items and Inspector buttons.
public class SelectionExample : Behaviour
{
[MenuItem("Tools/Drop Selection To Ground")]
static void DropToGround()
{
// gameObjects: every selected object.
foreach (GameObject go in Selection.gameObjects)
{
Vector3 p = go.transform.position;
go.transform.position = new Vector3(p.x, 0f, p.z);
}
// activeGameObject: the one clicked last, or null when nothing is selected.
GameObject last = Selection.activeGameObject;
Debug.Log(last == null ? "nothing selected" : "dropped " + Selection.gameObjects.Length + " objects; last was " + last.name);
}
}
AssetDatabase
static class AssetDatabase
The project's files, for menu items and editor windows (nothing in a game: there every call finds nothing). Paths are project-relative with forward slashes ("Textures/brick.png"); they cannot leave the project, name hidden files, or write into Library, ProjectSettings, Builds or Plugins.
| Member | Description | Example |
|---|---|---|
static bool Exists(string path) | Whether the file exists. | if (AssetDatabase.Exists("Reports/textures.txt")) |
static string[] FindAssets(string filter, string folder = "") | The project-relative paths of files whose name contains filter (any case; "t:png" lists a file type; empty lists every file), under folder (empty: the whole project). At most 5000. | string[] pictures = AssetDatabase.FindAssets("t:png", "Textures"); |
static string ReadAllText(string path) | A text file's contents, or null when there is none. | Debug.Log(AssetDatabase.ReadAllText("Reports/textures.txt")); |
static bool WriteAllText(string path, string text) | Writes a text file (its folders are made); false when the path is not allowed or the write failed. The Project window shows it a moment later. | if (!AssetDatabase.WriteAllText("Reports/textures.txt", report)) Debug.LogError("could not write the report"); |
static bool CopyAsset(string from, string to) | Copies a file to a new path (not over a file that is there); false when it cannot. | if (pictures.Length > 0) AssetDatabase.CopyAsset(pictures[0], "Textures/Backup/" + pictures.Length + ".png"); |
static void Refresh() | Does nothing: the Project window notices new files by itself. Here so scripts that call it compile. | AssetDatabase.Refresh(); |
Example (AssetDatabase.cs)
// AssetDatabase: the project's files, for editor tools (in a game every call finds nothing).
public class AssetDatabaseExample : Behaviour
{
[MenuItem("Tools/List Big Textures")]
static void WriteTextureList()
{
// FindAssets: project paths of files whose name contains the filter ("t:png" lists a file type), under a folder.
string[] pictures = AssetDatabase.FindAssets("t:png", "Textures");
string report = "Pictures in Textures/:\n" + string.Join("\n", pictures);
// WriteAllText: writes a text file (its folders are made); false when the path is not allowed.
if (!AssetDatabase.WriteAllText("Reports/textures.txt", report)) Debug.LogError("could not write the report");
// Exists: is there a file at this path? ReadAllText: a text file's contents, or null.
if (AssetDatabase.Exists("Reports/textures.txt"))
Debug.Log(AssetDatabase.ReadAllText("Reports/textures.txt"));
// CopyAsset: copies a file to a new path (never over one that is there).
if (pictures.Length > 0) AssetDatabase.CopyAsset(pictures[0], "Textures/Backup/" + pictures.Length + ".png");
// Refresh: does nothing here (the Project window notices new files itself); kept so scripts that call it compile.
AssetDatabase.Refresh();
}
}
Undo
static class Undo
For editor scripts that record their own undo steps: what a menu item, an Inspector button or an editor window changes is already one undo step, so these only keep such scripts compiling.
| Member | Description | Example |
|---|---|---|
static void RecordObject(object target, string name) | Does nothing: the changes are recorded for you. | Undo.RecordObject(go.transform, "Raise"); |
static void RegisterCreatedObjectUndo(object target, string name) | Does nothing: the changes are recorded for you. | Undo.RegisterCreatedObjectUndo(marker, "Raise marker"); |
static void SetCurrentGroupName(string name) | Does nothing: the whole run is one undo step. | Undo.SetCurrentGroupName("Raise selection"); |
Example (Undo.cs)
// Undo: the usual undo calls, kept so editor scripts that use them compile: here every editor change is already one undo step.
public class UndoExample : Behaviour
{
[MenuItem("Tools/Raise Selection")]
static void Raise()
{
GameObject go = Selection.activeGameObject;
if (go == null) return;
// RecordObject: does nothing (the change below is recorded for you).
Undo.RecordObject(go.transform, "Raise");
go.transform.position += Vector3.up;
GameObject marker = GameObject.Spawn("Sphere", go.transform.position + Vector3.up);
// RegisterCreatedObjectUndo: does nothing (the new object is part of the same undo step).
Undo.RegisterCreatedObjectUndo(marker, "Raise marker");
// SetCurrentGroupName: does nothing (the whole run is one step). Ctrl+Z takes all of it back.
Undo.SetCurrentGroupName("Raise selection");
}
}
Handles
static class Handles
Scene-view drawing for editor scripts: the same lines as Gizmos (the colour is its own), and handles you can drag: Slider and PositionHandle, called from a script's Behaviour.OnSceneGUI while its object is selected; they return the position the user dragged them to.
| Member | Description | Example |
|---|---|---|
static float GetHandleSize(Vector3 position) | A size that keeps a handle about as big on the screen wherever it is: grows with the distance from the camera. | float size = Handles.GetHandleSize(here); |
static Vector3 Slider(Vector3 position, Vector3 direction, float size = 1f) | An arrow along direction, size long, that the user drags along its line; returns the position it is dragged to (the one it was given while nobody drags it). | Vector3 edge = Handles.Slider(here + Vector3.right * range, Vector3.right, size); |
static Vector3 PositionHandle(Vector3 position) | Three arrows (red x, green y, blue z) at position; returns where the user dragged it. | Vector3 exitWorld = Handles.PositionHandle(here + exit); |
static Color color | The colour of what is drawn next. | Handles.color = Color.yellow; |
static void DrawLine(Vector3 from, Vector3 to) | A line between two points. | Handles.DrawLine(here, exitWorld); |
static void DrawPolyLine(params Vector3[] points) | Lines joining the points in order. | Handles.DrawPolyLine(exitWorld, exitWorld + Vector3.up, exitWorld + Vector3.up + Vector3.right * 0.5f); |
static void DrawWireDisc(Vector3 center, Vector3 normal, float radius) | A circle around normal. | Handles.DrawWireDisc(here, Vector3.up, range); |
Example (Handles.cs)
// Handles: handles you can drag in the Scene view, drawn from a script's OnSceneGUI while its object is selected.
public class HandlesExample : Behaviour
{
public float range = 5f;
public Vector3 exit = new Vector3(3f, 0f, 0f); // a point other objects are sent to, relative to this one
public override void OnSceneGUI()
{
Vector3 here = transform.position;
// color: the colour of what is drawn next.
Handles.color = Color.yellow;
// DrawWireDisc: a circle about a normal: the range, flat on the ground.
Handles.DrawWireDisc(here, Vector3.up, range);
// GetHandleSize: a size that keeps a handle about as big on screen wherever it is.
float size = Handles.GetHandleSize(here);
// Slider: an arrow the user drags along its line; it returns where it was dragged to. Here it sets the range.
Vector3 edge = Handles.Slider(here + Vector3.right * range, Vector3.right, size);
range = Mathf.Max(0.5f, edge.x - here.x);
// PositionHandle: three arrows at a point; it returns where the user dragged it.
Vector3 exitWorld = Handles.PositionHandle(here + exit);
exit = exitWorld - here;
Handles.color = Color.cyan;
// DrawLine: a line between two points. DrawPolyLine: lines joining any number of points in order.
Handles.DrawLine(here, exitWorld);
Handles.DrawPolyLine(exitWorld, exitWorld + Vector3.up, exitWorld + Vector3.up + Vector3.right * 0.5f);
}
}
CustomEditorAttribute
class CustomEditorAttribute : Attribute
Makes an Editor class the Inspector of a script class: [CustomEditor(typeof(Spinner))]. It draws that script's Inspector in the editor (never in the game).
| Member | Description | Example |
|---|---|---|
readonly Type type | The script class it draws. | GUILayout.Label("Inspector for " + a.type.Name); |
CustomEditorAttribute(Type type) | An Inspector for scripts of this class. | [CustomEditor(typeof(CustomEditorAttributeExample))] |
Example (CustomEditorAttribute.cs)
// CustomEditorAttribute: makes an Editor class the Inspector of a script class.
public class CustomEditorAttributeExample : Behaviour
{
public float speed = 90f;
public bool clockwise = true;
}
// The Inspector of CustomEditorAttributeExample: drawn by this class instead of the usual fields.
[CustomEditor(typeof(CustomEditorAttributeExample))]
public class CustomEditorAttributeExampleEditor : Editor
{
public override void OnInspectorGUI()
{
var spinner = (CustomEditorAttributeExample)target;
spinner.speed = EditorGUILayout.Slider("Speed", spinner.speed, 0f, 720f);
spinner.clockwise = EditorGUILayout.Toggle("Clockwise", spinner.clockwise);
// type: the script class an attribute names.
CustomEditorAttribute a = new CustomEditorAttribute(typeof(CustomEditorAttributeExample));
GUILayout.Label("Inspector for " + a.type.Name);
}
}
Editor
class Editor
A script's own Inspector, drawn by code: derive from it, mark it [CustomEditor(typeof(MyScript))] and override OnInspectorGUI with GUILayout and EditorGUILayout calls. It runs in the editor while the Inspector shows an object with that script, and again after each change the user makes; what it changes in the script's fields and in the scene is one undo step.
| Member | Description | Example |
|---|---|---|
Behaviour target | The script being inspected (cast it to its class). | EditorExampleTurret turret = (EditorExampleTurret)target; |
virtual void OnInspectorGUI() | Draws the Inspector; by default the script's usual fields. | public override void OnInspectorGUI() |
void DrawDefaultInspector() | Puts the script's usual fields here. | DrawDefaultInspector(); |
Example (Editor.cs)
// Editor: a script's own Inspector, drawn by code.
public class EditorExampleTurret : Behaviour
{
public float range = 10f;
public int ammo = 20;
public Color beam = Color.red;
}
[CustomEditor(typeof(EditorExampleTurret))]
public class EditorExample : Editor
{
// OnInspectorGUI: draws the Inspector (by default: the script's usual fields).
public override void OnInspectorGUI()
{
// target: the script being inspected; cast it to its class.
EditorExampleTurret turret = (EditorExampleTurret)target;
// DrawDefaultInspector: puts the script's usual fields here, then add your own controls under them.
DrawDefaultInspector();
EditorGUILayout.Separator();
if (turret.ammo == 0) EditorGUILayout.HelpBox("This turret starts empty.", MessageType.Warning);
if (GUILayout.Button("Fill Ammo")) turret.ammo = 100;
EditorGUILayout.LabelField("Covers", Mathf.RoundToInt(Mathf.PI * turret.range * turret.range) + " square metres");
}
}
EditorWindow
class EditorWindow
A panel of the editor drawn by code: derive from it, override OnGUI, and open it from a menu item with EditorWindow.GetWindow<MyWindow>("My Tool"). It shows as a tab beside the Console until it is closed; its fields keep their values until the scripts change. What it changes in the scene is one undo step.
| Member | Description | Example |
|---|---|---|
string title | The window's title (its tab). | Debug.Log("opened " + w.title); |
virtual void OnGUI() | Draws the window with GUILayout and EditorGUILayout. | public override void OnGUI() |
static T GetWindow<T>(string title = null) where T : EditorWindow, new() | Opens the window of this class (or the one open already) and returns it. | EditorWindowExample w = EditorWindow.GetWindow<EditorWindowExample>("Rename Tool"); |
void Close() | Closes it. | if (GUILayout.Button("Done")) Close(); |
Example (EditorWindow.cs)
// EditorWindow: a panel of the editor drawn by code, opened from a menu item.
public class EditorWindowExample : EditorWindow
{
string prefix = "Enemy";
int count;
// Tools > Rename Tool opens the window.
[MenuItem("Tools/Rename Tool")]
static void Open()
{
// GetWindow: opens the window of this class (or brings up the one already open) and returns it.
EditorWindowExample w = EditorWindow.GetWindow<EditorWindowExample>("Rename Tool");
// title: the text on its tab.
Debug.Log("opened " + w.title);
}
// OnGUI: draws the window, top to bottom.
public override void OnGUI()
{
prefix = EditorGUILayout.TextField("Prefix", prefix);
if (GUILayout.Button("Rename Selection"))
{
count = 0;
foreach (GameObject go in Selection.gameObjects) go.name = prefix + " " + (++count);
}
GUILayout.Label(count + " renamed");
// Close: closes the window.
if (GUILayout.Button("Done")) Close();
}
}
MessageType
enum MessageType
How a help box looks.
| Member | Description | Example |
|---|---|---|
None | Plain text. | EditorGUILayout.HelpBox("Doors turn about their hinge edge.", MessageType.None); |
Info | A note. | EditorGUILayout.HelpBox("Hold Shift while dragging to snap the angle.", MessageType.Info); |
Warning | Something to watch out for. | if (door.openAngle > 170f) EditorGUILayout.HelpBox("An angle this wide swings the door through the wall.", ... |
Error | Something wrong. | if (door.key == null) EditorGUILayout.HelpBox("No key is set: this door can never be opened.", MessageType.... |
Example (MessageType.cs)
// MessageType: how a help box in a custom Inspector or editor window looks.
public class MessageTypeExampleDoor : Behaviour
{
public GameObject key;
public float openAngle = 90f;
}
[CustomEditor(typeof(MessageTypeExampleDoor))]
public class MessageTypeExample : Editor
{
public override void OnInspectorGUI()
{
MessageTypeExampleDoor door = (MessageTypeExampleDoor)target;
DrawDefaultInspector();
// None: plain text. Info: a note. Warning: something to watch out for. Error: something wrong.
EditorGUILayout.HelpBox("Doors turn about their hinge edge.", MessageType.None);
EditorGUILayout.HelpBox("Hold Shift while dragging to snap the angle.", MessageType.Info);
if (door.openAngle > 170f) EditorGUILayout.HelpBox("An angle this wide swings the door through the wall.", MessageType.Warning);
if (door.key == null) EditorGUILayout.HelpBox("No key is set: this door can never be opened.", MessageType.Error);
}
}
GUILayout
static class GUILayout
Plain controls for custom Inspectors and editor windows, drawn one under the other.
| Member | Description | Example |
|---|---|---|
static void Label(string text) | A line of text. | GUILayout.Label("Clicked " + clicks + " times"); |
static bool Button(string text) | A button: true in the call after it was pressed. | if (GUILayout.Button("Click me")) clicks++; |
static void Space(float pixels = 8f) | Empty room, in pixels. | GUILayout.Space(12f); |
Example (GUILayout.cs)
// GUILayout: plain controls for custom Inspectors and editor windows, laid out one under the other.
public class GUILayoutExample : EditorWindow
{
int clicks;
[MenuItem("Tools/Click Counter")]
static void Open() { EditorWindow.GetWindow<GUILayoutExample>("Click Counter"); }
public override void OnGUI()
{
// Label: a line of text.
GUILayout.Label("Clicked " + clicks + " times");
// Space: empty room, in pixels (8 when left out).
GUILayout.Space(12f);
// Button: true in the call after it was pressed.
if (GUILayout.Button("Click me")) clicks++;
GUILayout.Space();
if (GUILayout.Button("Reset")) clicks = 0;
}
}
EditorGUILayout
static class EditorGUILayout
Labelled fields for custom Inspectors and editor windows. Each returns the value to keep: the one passed in, or what the user just set it to.
| Member | Description | Example |
|---|---|---|
static float FloatField(string label, float value) | A number. | spacing = EditorGUILayout.FloatField("Spacing", spacing); |
static int IntField(string label, int value) | A whole number. | rows = EditorGUILayout.IntField("Rows", rows); |
static float Slider(string label, float value, float min, float max) | A number between min and max, set with a slider. | jitter = EditorGUILayout.Slider("Jitter", jitter, 0f, 1f); |
static int IntSlider(string label, int value, int min, int max) | A whole number between min and max, set with a slider. | columns = EditorGUILayout.IntSlider("Columns", columns, 1, 20); |
static bool Toggle(string label, bool value) | A switch. | randomTurn = EditorGUILayout.Toggle("Random turn", randomTurn); |
static string TextField(string label, string value) | A line of text. | baseName = EditorGUILayout.TextField("Name", baseName); |
static Vector3 Vector3Field(string label, Vector3 value) | Three numbers. | origin = EditorGUILayout.Vector3Field("Origin", origin); |
static Color ColorField(string label, Color value) | A colour, picked with the editor's colour picker. | tint = EditorGUILayout.ColorField("Tint", tint); |
static int Popup(string label, int selected, string[] options) | One of options, by its index. | shape = EditorGUILayout.Popup("Shape", shape, shapes); |
static void LabelField(string label, string text) | A label and, beside it, a value to read. | EditorGUILayout.LabelField("Objects", (rows * columns).ToString()); |
static void HelpBox(string message, MessageType type) | A box with a message. | EditorGUILayout.HelpBox("Makes a grid of objects in the open scene.", MessageType.Info); |
static void Space() | A little empty room. | EditorGUILayout.Space(); |
static void Separator() | A thin line across. | EditorGUILayout.Separator(); |
Example (EditorGUILayout.cs)
// EditorGUILayout: labelled fields for custom Inspectors and editor windows; each returns the value to keep.
public class EditorGUILayoutExample : EditorWindow
{
float spacing = 2f;
int rows = 3;
float jitter = 0.2f;
int columns = 4;
bool randomTurn = true;
string baseName = "Crate";
Vector3 origin = Vector3.zero;
Color tint = Color.white;
int shape;
readonly string[] shapes = { "Cube", "Sphere", "Cylinder" };
[MenuItem("Tools/Grid Maker")]
static void Open() { EditorWindow.GetWindow<EditorGUILayoutExample>("Grid Maker"); }
public override void OnGUI()
{
// HelpBox: a box with a message.
EditorGUILayout.HelpBox("Makes a grid of objects in the open scene.", MessageType.Info);
// TextField: a line of text. Popup: one of a list, by its index.
baseName = EditorGUILayout.TextField("Name", baseName);
shape = EditorGUILayout.Popup("Shape", shape, shapes);
// IntField: a whole number. IntSlider: a whole number between two values.
rows = EditorGUILayout.IntField("Rows", rows);
columns = EditorGUILayout.IntSlider("Columns", columns, 1, 20);
// FloatField: a number. Slider: a number between two values.
spacing = EditorGUILayout.FloatField("Spacing", spacing);
jitter = EditorGUILayout.Slider("Jitter", jitter, 0f, 1f);
// Toggle: a switch. Vector3Field: three numbers. ColorField: a colour from the colour picker.
randomTurn = EditorGUILayout.Toggle("Random turn", randomTurn);
origin = EditorGUILayout.Vector3Field("Origin", origin);
tint = EditorGUILayout.ColorField("Tint", tint);
// Separator: a thin line across. Space: a little empty room.
EditorGUILayout.Separator();
// LabelField: a label with a value to read beside it.
EditorGUILayout.LabelField("Objects", (rows * columns).ToString());
EditorGUILayout.Space();
if (!GUILayout.Button("Make Grid")) return;
for (int r = 0; r < rows; r++)
for (int c = 0; c < columns; c++)
{
Vector3 p = origin + new Vector3(c * spacing + Random.Range(-jitter, jitter), 0.5f, r * spacing + Random.Range(-jitter, jitter));
GameObject go = GameObject.Spawn(shapes[shape], p);
go.name = baseName + " " + (r * columns + c + 1);
go.SetColor(tint);
if (randomTurn) go.transform.rotation = new Vector3(0f, Random.Range(0f, 360f), 0f);
}
}
}
DataAsset
class DataAsset
Game data kept in a project file instead of on an object. Derive a class from it with public fields, select its script in the Project window and press CREATE ... ASSET: each .asset file is one set of values (a sword, an axe) filled in in the Inspector. A script field of the class picks one of those files, and every script naming the same file shares one instance.
| Member | Description | Example |
|---|---|---|
string path | The project path of the file these values came from, for example "Data/Sword.asset". | Debug.Log(w.name + " (" + w.path + "): " + w.title + " does " + w.damage + " at " + w.reach + " m; " + w.To... |
string name | The file name without its extension ("Sword"). | Debug.Log(w.name + " (" + w.path + "): " + w.title + " does " + w.damage + " at " + w.reach + " m; " + w.To... |
static T Load<T>(string path) where T : DataAsset | The data asset at a project path, or null (with a warning) when there is none or it holds another class. | DataAssetExampleWeapon sword = DataAsset.Load<DataAssetExampleWeapon>("Data/Sword.asset"); |
static List<T> LoadAll<T>() where T : DataAsset | Every data asset of class T (or a class deriving from it) in the project, in path order. | List<DataAssetExampleWeapon> all = DataAsset.LoadAll<DataAssetExampleWeapon>(); |
override string ToString() | The asset's project path. | Debug.Log(w.name + " (" + w.path + "): " + w.title + " does " + w.damage + " at " + w.reach + " m; " + w.To... |
Example (DataAsset.cs)
// DataAsset: game data kept in a project file instead of on an object.
using System.Collections.Generic;
// A kind of data: derive from DataAsset with public fields. In the Project window, create a data asset of this class
// ("Data/Sword.asset") and fill its fields in the Inspector.
public class DataAssetExampleWeapon : DataAsset
{
public string title = "Sword";
public int damage = 10;
public float reach = 1.5f;
}
public class DataAssetExample : Behaviour
{
// A field of the class shows in the Inspector as a slot for one of its assets.
public DataAssetExampleWeapon held;
public override void Start()
{
// Load: the data asset at a project path (null, with a warning, when there is none or it is another class).
DataAssetExampleWeapon sword = DataAsset.Load<DataAssetExampleWeapon>("Data/Sword.asset");
if (held == null) held = sword;
// LoadAll: every data asset of the class in the project, in path order: the shop's whole list.
List<DataAssetExampleWeapon> all = DataAsset.LoadAll<DataAssetExampleWeapon>();
foreach (DataAssetExampleWeapon w in all)
// path: the file the values came from. name: its file name without the extension. ToString: the path.
Debug.Log(w.name + " (" + w.path + "): " + w.title + " does " + w.damage + " at " + w.reach + " m; " + w.ToString());
}
}
DataTable
class DataTable
A table from a CSV file in the project: the first row names the columns, the first column names the rows; the editor edits it as a grid. DataTable.Load("Data/Weapons.csv").GetFloat("Sword", "Damage"), or a whole row into a class with fields named as the columns: table.GetRow<Weapon>("Sword").
| Member | Description | Example |
|---|---|---|
string path | The project path of the file. | Debug.Log(enemies.path + " has columns " + string.Join(", ", enemies.columns) + " and rows " + string.Join(... |
string[] columns | The column names, the row-name column first. | Debug.Log(enemies.path + " has columns " + string.Join(", ", enemies.columns) + " and rows " + string.Join(... |
string[] rows | The row names, in the file's order. | Debug.Log(enemies.path + " has columns " + string.Join(", ", enemies.columns) + " and rows " + string.Join(... |
static DataTable Load(string path) | The table at a project path, or null (with a warning) when there is none. | DataTable enemies = DataTable.Load("Data/Enemies.csv"); |
bool Has(string row) | Whether it has a row of that name. | if (!enemies.Has("Goblin")) return; |
string Get(string row, string column) | The text in a row's column ("" when there is no such row or column). | string weapon = enemies.Get("Goblin", "weapon"); |
float GetFloat(string row, string column) | A cell as a number (0 when it is empty or not a number). | float speed = enemies.GetFloat("Goblin", "speed"); |
int GetInt(string row, string column) | A cell as a whole number (0 when it is empty or not a number). | int health = enemies.GetInt("Goblin", "health"); |
T GetRow<T>(string row) where T : new() | A row as an object of class T: each public field named as a column gets that cell (numbers, true/false, text, enum names). Null when there is no such row. | DataTableExampleEnemy troll = enemies.GetRow<DataTableExampleEnemy>("Troll"); |
Example (DataTable.cs)
// DataTable: a table from a CSV file: the first row names the columns, the first column names the rows.
public class DataTableExampleEnemy
{
public int health;
public float speed;
public string weapon;
}
public class DataTableExample : Behaviour
{
public override void Start()
{
// Load: the table at a project path (null, with a warning, when there is none).
// Data/Enemies.csv: name,health,speed,weapon / Goblin,30,3.5,Club / Troll,120,1.2,Rock
DataTable enemies = DataTable.Load("Data/Enemies.csv");
// path: the file. columns: the column names (the row-name column first). rows: the row names in file order.
Debug.Log(enemies.path + " has columns " + string.Join(", ", enemies.columns) + " and rows " + string.Join(", ", enemies.rows));
// Has: is there a row of that name?
if (!enemies.Has("Goblin")) return;
// Get: a cell's text. GetInt, GetFloat: a cell as a number (0 when empty or not a number).
string weapon = enemies.Get("Goblin", "weapon");
int health = enemies.GetInt("Goblin", "health");
float speed = enemies.GetFloat("Goblin", "speed");
Debug.Log("a goblin has " + health + " health, runs at " + speed + " and carries a " + weapon);
// GetRow: a whole row as an object: each public field named like a column gets that cell.
DataTableExampleEnemy troll = enemies.GetRow<DataTableExampleEnemy>("Troll");
Debug.Log("a troll: " + troll.health + " health, " + troll.speed + " speed, " + troll.weapon);
}
}
Transform
class Transform
Position, rotation and scale of an object.
| Member | Description | Example |
|---|---|---|
GameObject gameObject | The object this transform belongs to. | Debug.Log("moving " + t.gameObject.name); |
Vector3 position | World position. | t.position = new Vector3(0f, 1f, 0f); |
Vector3 rotation | Euler angles in degrees (rotation order: Z, then X, then Y). | t.rotation = new Vector3(0f, 90f, 0f); |
Vector3 eulerAngles | Same as rotation: Euler angles in degrees (the other common spelling). | t.eulerAngles = new Vector3(0f, 90f, 0f); |
Vector3 scale | Local scale. | t.scale = new Vector3(1f, 2f, 1f); |
Vector3 localPosition | Position relative to the parent object (the world position when there is no parent): a weapon in a hand, a camera on a rig. Setting it places the object where that local position lands in the world right now. | t.localPosition = new Vector3(0.3f, 0f, 0f); |
Vector3 localRotation | Euler angles in degrees relative to the parent object (the world rotation when there is none). | t.localRotation = new Vector3(0f, 0f, 15f); |
Vector3 localScale | Scale relative to the parent object (the scale itself when there is none). | t.localScale = Vector3.one; |
Vector3 forward | Where this object's local -Z points, in world space. | Vector3 ahead = t.forward; |
Vector3 right | The local +X axis in world space. | Vector3 side = t.right; |
Vector3 up | The local +Y axis in world space. | Vector3 above = t.up; |
void Translate(Vector3 delta) | Moves by delta in world space. | if (Input.GetKey("Up")) t.Translate(ahead * speed * deltaTime); |
void TranslateLocal(Vector3 delta) | Moves by delta in this object's own axes. | if (Input.GetKey("W")) t.TranslateLocal(new Vector3(0f, 0f, -speed * deltaTime)); |
void Rotate(Vector3 eulerDelta) | Adds eulerDelta degrees to the rotation. | t.Rotate(new Vector3(0f, Input.GetAxis("Horizontal") * 90f * deltaTime, 0f)); |
void RotateAround(Vector3 point, Vector3 axis, float degrees) | Turns the object about a point in the world, like a door on its hinge or a chest lid on its back edge: its position swings round point about axis (a direction, e.g. Vector3.up) by degrees, and it turns with it. Call it with the change since the last frame, not the total. | if (Input.GetKey("O")) t.RotateAround(target.transform.position, Vector3.up, 45f * deltaTime); |
void LookAt(Vector3 target) | Turns so that -Z faces target (yaw and pitch). | if (Input.GetKey("L")) t.LookAt(target.transform.position); |
void LookAt(Transform target) | Turns to face another object. | if (Input.GetKey("L")) t.LookAt(target.transform.position); |
Transform parent | The transform of the object this one is parented to (null at the top); setting it re-parents. | if (t.parent == null && target != null) t.SetParent(target.transform); |
void SetParent(Transform p) | Re-parents this object under another (null: to the top). | if (t.parent == null && target != null) t.SetParent(target.transform); |
Transform root | The topmost object above this one (itself when it has no parent). | Debug.Log("top of the tree: " + t.root.gameObject.name); |
int childCount | How many objects are parented directly under this one. | for (int i = 0; i < t.childCount; i++) Debug.Log("child " + t.GetChild(i).gameObject.name); |
Transform GetChild(int index) | The child at index (0 is the first), or null. | for (int i = 0; i < t.childCount; i++) Debug.Log("child " + t.GetChild(i).gameObject.name); |
Transform Find(string name) | A child by name, or a path under it ("Arm/Hand"); null when there is none. | Transform hand = t.Find("Arm/Hand"); |
bool IsChildOf(Transform p) | True when this object is p or somewhere under it. | if (hand != null && hand.IsChildOf(t)) hand.GetComponent<Light>(); |
T GetComponent<T>() where T : class | A part of this object (see GameObject.GetComponent). | if (hand != null && hand.IsChildOf(t)) hand.GetComponent<Light>(); |
Example (Transform.cs)
// Transform: where an object is, how it is turned and how big it is.
public class TransformExample : Behaviour
{
public GameObject target;
public float speed = 3f;
public override void Start()
{
Transform t = transform;
// gameObject: the object this transform belongs to.
Debug.Log("moving " + t.gameObject.name);
// position: where it is in the world. rotation (eulerAngles): degrees about x, y, z. scale: its size.
t.position = new Vector3(0f, 1f, 0f);
t.rotation = new Vector3(0f, 90f, 0f);
t.eulerAngles = new Vector3(0f, 90f, 0f); // the same thing, the other common spelling
t.scale = new Vector3(1f, 2f, 1f);
// localPosition, localRotation, localScale: the same three relative to the parent (a sword in a hand).
t.localPosition = new Vector3(0.3f, 0f, 0f);
t.localRotation = new Vector3(0f, 0f, 15f);
t.localScale = Vector3.one;
}
public override void Update(float deltaTime)
{
Transform t = transform;
// forward, right, up: the object's own axes in the world (forward is its -Z).
Vector3 ahead = t.forward;
Vector3 side = t.right;
Vector3 above = t.up;
// Translate: move by an amount in the world. TranslateLocal: move along the object's own axes.
if (Input.GetKey("Up")) t.Translate(ahead * speed * deltaTime);
if (Input.GetKey("Right")) t.Translate(side * speed * deltaTime);
if (Input.GetKey("Space")) t.Translate(above * speed * deltaTime);
if (Input.GetKey("W")) t.TranslateLocal(new Vector3(0f, 0f, -speed * deltaTime));
// Rotate: add degrees to the rotation.
t.Rotate(new Vector3(0f, Input.GetAxis("Horizontal") * 90f * deltaTime, 0f));
if (target == null) return;
// RotateAround: turn about a point in the world (a moon round a planet, a door on its hinge).
if (Input.GetKey("O")) t.RotateAround(target.transform.position, Vector3.up, 45f * deltaTime);
// LookAt: turn to face a point, or another object's transform.
if (Input.GetKey("L")) t.LookAt(target.transform.position);
if (Input.GetKey("K")) t.LookAt(target.transform);
}
public override void Awake()
{
Transform t = transform;
// parent, root: the transform above this one (null at the top) and the topmost one. SetParent: move it under another.
if (t.parent == null && target != null) t.SetParent(target.transform);
Debug.Log("top of the tree: " + t.root.gameObject.name);
// childCount, GetChild: the objects directly under it. Find: one by name, or a path under it ("Arm/Hand").
for (int i = 0; i < t.childCount; i++) Debug.Log("child " + t.GetChild(i).gameObject.name);
Transform hand = t.Find("Arm/Hand");
// IsChildOf: whether it is under another (or is it). GetComponent: a part of the object, as GameObject's.
if (hand != null && hand.IsChildOf(t)) hand.GetComponent<Light>();
}
}
GameObject
class GameObject
An object in the scene.
| Member | Description | Example |
|---|---|---|
Transform transform | The object's transform. | me.transform.position = Vector3.zero; |
string name | The object name. | Debug.Log(me.name + " tagged '" + me.tag + "' on layer " + me.layer); |
bool active | Whether the object is active. | door.active = false; |
void SetActive(bool value) | Same as setting active (the other common spelling). | door.SetActive(true); |
bool enabled | Same as active (the spelling components use elsewhere). | marker.enabled = true; |
Animator animator | The object's Animator (plays its animation clip), or null. | if (player.animator != null) player.animator.Play(); |
NavAgent agent | The object's NavAgent (walks it around obstacles), or null. | if (enemies.Count > 0 && enemies[0].agent != null) enemies[0].agent.SetDestination(player.transform.position); |
CharacterController character | The object's CharacterController (walks and jumps it), or null. | if (player.character != null) player.character.Jump(); |
ModelAnimation model | The object's skinned model animation (ModelAnimator): go.model.Play("Attack") plays a clip once over whatever it is doing (walking, idling) and then lets go. | if (player.model != null) player.model.Play("Wave"); |
GameObject parent | The object this one is parented to, or null. | Debug.Log(pillar.parent.name + " now has " + me.children.Count + " children"); |
List<GameObject> children | Objects parented directly under this one. | Debug.Log(pillar.parent.name + " now has " + me.children.Count + " children"); |
void SetParent(GameObject p) | Re-parents this object (null = scene root). | pillar.SetParent(me); |
string tag | Free-form label set in the Inspector (Tag field). | Debug.Log(me.name + " tagged '" + me.tag + "' on layer " + me.layer); |
bool CompareTag(string t) | True when the object has this tag. | if (me.CompareTag("Player")) Debug.Log(enemies.Count + " enemies, " + torches.Count + " torches"); |
int layer | The object's layer, 0..31 (the Layer field of the Inspector; names via LayerMask.LayerToName). Raycasts and OverlapSphere can skip layers with a mask, and Project Settings > Physics says which layers collide. | Debug.Log(me.name + " tagged '" + me.tag + "' on layer " + me.layer); |
T GetComponent<T>() where T : class | A part of this object, or null when it has none: one of its scripts (GetComponent<Health>()), its Transform, Rigidbody, Animator, CharacterController, NavAgent, AudioSource, Light, MeshRenderer, Collider, or what a UI object is (UIText, UIButton, UIImage, UISlider, UIToggle, UIInput). | GameObjectExampleHealth same = player.GetComponent<GameObjectExampleHealth>(); |
Component GetComponent(string type) | A built-in component by its Inspector name (GetComponent("ParticleSystem")), to change its fields with Set; null when the object has none. | GameObjectExampleHealth same = player.GetComponent<GameObjectExampleHealth>(); |
bool TryGetComponent<T>(out T component) where T : class | True when the object has that part, and it in component. | if (me.TryGetComponent(out Light lamp)) lamp.intensity = 2f; |
List<T> GetComponents<T>() where T : class | Every script of type T on this object (a built-in part is listed once). | Debug.Log(me.GetComponents<GameObjectExampleHealth>().Count + " health scripts"); |
T GetComponentInChildren<T>(bool includeInactive = false) where T : class | The part on this object or the first of the objects under it that has one (switched-off ones are skipped unless includeInactive). | Collider hitBox = me.GetComponentInChildren<Collider>(); |
List<T> GetComponentsInChildren<T>(bool includeInactive = false) where T : class | That part on this object and every object under it. | List<MeshRenderer> looks = me.GetComponentsInChildren<MeshRenderer>(); |
T GetComponentInParent<T>() where T : class | The part on this object or the nearest object above it that has one. | GameObjectExampleHealth owner = me.GetComponentInParent<GameObjectExampleHealth>(); |
bool HasComponent(string type) | True when the object has the component with this Inspector name ("RigidBody", "AudioSource"). | if (hitBox != null && me.HasComponent("RigidBody")) Debug.Log(looks.Count + " looks, owned: " + (owner != n... |
static GameObject FindGameObjectWithTag(string t) | The first object with this tag, or null (the same as FindWithTag(tag)[0]). | GameObject goal = GameObject.FindGameObjectWithTag("Finish"); |
static GameObject[] FindGameObjectsWithTag(string t) | Every object carrying the tag, as an array. | GameObject[] spawns = GameObject.FindGameObjectsWithTag("Respawn"); |
bool activeSelf | Whether this object itself is switched on (its parents may still be off). | if (goal != null && goal.activeSelf && goal.activeInHierarchy) Debug.Log(spawns.Length + " spawn points"); |
bool activeInHierarchy | Whether this object and every object above it are switched on. | if (goal != null && goal.activeSelf && goal.activeInHierarchy) Debug.Log(spawns.Length + " spawn points"); |
static List<GameObject> FindWithTag(string t) | All objects carrying the tag. | List<GameObject> enemies = GameObject.FindWithTag("Enemy"); |
bool exists | False once the object was destroyed. | Debug.Log("box2 exists until the end of this frame: " + box2.exists); |
static GameObject Find(string name) | The first object with this name, or null. A path picks an object by its parents: Find("Player/Player Model") is the "Player Model" whose parent is "Player" (a leading "/" or "Root/" is fine too). When several objects share a plain name the first one is returned and a warning says so once: name the one you mean with a path. | GameObject door = GameObject.Find("Door"); |
static GameObject FindPlayer() | The player: the first object with a CharacterController (the part that actually walks, even when an empty "Player" object holds it), else the object called "Player", else null. | GameObject player = GameObject.FindPlayer(); |
void SendMessage(string method, object arg = null) | Calls the method with this name on every script of this object that has it (private ones too), with arg when the method takes one: how one script tells another on the same object that something happened (go.SendMessage("OnInteract", player)). | door.SendMessage("Open"); |
static List<GameObject> FindAll(string name) | Every object with this name. | List<GameObject> torches = GameObject.FindAll("Torch"); |
static List<GameObject> All() | Every object in the scene. | Debug.Log(GameObject.All().Count + " objects in the scene"); |
static GameObject Spawn(string mesh) | Creates a primitive: "Cube", "Sphere", "Plane", "Cylinder", "Capsule", "Cone", "Torus", or "" for an empty object. | GameObject marker = GameObject.Spawn("Sphere"); |
static GameObject Spawn(string mesh, Vector3 position) | Creates an object at a position. | GameObject marker = GameObject.Spawn("Sphere"); |
static GameObject Spawn(string mesh, Vector3 position, Vector3 rotation, Vector3 scale) | Creates an object with a position, rotation (degrees) and scale. | GameObject marker = GameObject.Spawn("Sphere"); |
static GameObject Instantiate(Prefab prefab, Vector3 position) | Instantiates a prefab field (a public Prefab bullet; set in the Inspector). | GameObject box = GameObject.Instantiate(crate, new Vector3(1f, 0f, 1f)); |
static GameObject Spawn(Mesh mesh, Vector3 position) | Spawns a model field (a public Mesh body; set in the Inspector). | GameObject marker = GameObject.Spawn("Sphere"); |
static GameObject Instantiate(string prefabPath, Vector3 position) | Instantiates a prefab asset, e.g. "Prefabs/Crate.prefab", with its root at position (x, z on the ground). | GameObject box = GameObject.Instantiate(crate, new Vector3(1f, 0f, 1f)); |
static void Destroy(GameObject go) | Removes the object (and its scripts) at the end of the frame. | GameObject.Destroy(box2); |
Rigidbody rigidbody | Pushes and reads the physics body of this object (the RigidBody component, or one made with AddRigidbody). | marker.rigidbody.AddImpulse(Vector3.up * 5f); |
void AddRigidbody(float mass = 1f) | Gives an object made with Spawn a physics body of its own that falls, bounces and is pushed, with a collider that fits its mesh (box, sphere or capsule). Call it right after Spawn. | marker.AddRigidbody(2f); |
void SetColor(Vector3 rgb) | Tints the object's surface while playing: its material colour is multiplied by this colour (0..1 per channel; new Vector3(1, 1, 1) is no tint). A hit flash: go.SetColor(new Vector3(1f, 0.3f, 0.3f)). | marker.SetColor(new Vector3(1f, 0.3f, 0.3f)); |
void SetColor(Color c) | Tints the object's surface with a colour (its red, green and blue; alpha is not used): go.SetColor(Color.red). | marker.SetColor(new Vector3(1f, 0.3f, 0.3f)); |
void SetModelPart(string part, Vector3 eulerDegrees) | Turns one named part of a model (a wheel, a turret, a door in the glTF file) by these Euler degrees from its resting pose, while playing. The part names are the ones model_info lists. Set it every frame to spin: go.SetModelPart("Wheel_FL", new Vector3(angle, 0, 0)). | oak.SetModelPart("Crown", new Vector3(0f, 15f, 0f)); |
void AddCollider() | Gives an object made with Spawn a fixed collider (a wall, a floor) that bodies bump into. | ramp.AddCollider(); |
void AddComponent(string component) | Adds a component with its usual starting values while playing, e.g. go.AddComponent("ParticleSystem"), go.AddComponent("PointLight"), go.AddComponent("AudioSource"); then change its fields with Set. | marker.AddComponent("PointLight"); |
void RemoveComponent(string component) | Takes a component off the object while playing (switches a light or an emitter off for good). | box.RemoveComponent("AudioSource"); |
void Set(string component, string field, float value) | Changes a number field of one of this object's components while playing, e.g. go.Set("PointLight", "intensity", 3f), go.Set("Camera", "fov", 75f), go.Set("ParticleSystem", "rate", 80f). Names are the component and field names of the Inspector. | marker.Set("PointLight", "intensity", 3f); |
void Set(string component, string field, bool value) | Changes a true/false field, e.g. go.Set("ParticleSystem", "looping", false). | marker.Set("PointLight", "intensity", 3f); |
void Set(string component, string field, string value) | Changes a text field, e.g. go.Set("SpriteRenderer", "texture", "Sprites/Hit.png"). | marker.Set("PointLight", "intensity", 3f); |
void Set(string component, string field, Vector3 value) | Changes a colour or vector field, e.g. go.Set("PointLight", "color", new Vector3(1f, 0.2f, 0.1f)). | marker.Set("PointLight", "intensity", 3f); |
void SetMaterial(string projectPath) | Assigns a project material, e.g. "Materials/Gold.mat". | pillar.SetMaterial("Materials/Stone.mat"); |
T GetScript<T>() where T : Behaviour | The first script of type T on this object, or null. | GameObjectExampleHealth hp = player.GetScript<GameObjectExampleHealth>(); |
Example (GameObject.cs)
// GameObject: an object in the scene: finding, making, changing and removing objects from a script.
using System.Collections.Generic;
public class GameObjectExample : Behaviour
{
public Prefab crate;
public Mesh tree;
public override void Start()
{
GameObject me = gameObject;
// name, tag, layer: what the object is called, its free-form tag, and its layer (0..31).
Debug.Log(me.name + " tagged '" + me.tag + "' on layer " + me.layer);
// transform: where it is.
me.transform.position = Vector3.zero;
// ---- finding objects ----
// Find: the first object with a name (a path picks by parents: "Player/Model"). FindAll: every one with it.
GameObject door = GameObject.Find("Door");
List<GameObject> torches = GameObject.FindAll("Torch");
// FindWithTag: every object carrying a tag. CompareTag: does this one carry it?
List<GameObject> enemies = GameObject.FindWithTag("Enemy");
if (me.CompareTag("Player")) Debug.Log(enemies.Count + " enemies, " + torches.Count + " torches");
// FindPlayer: the object that walks as the player (the one with a CharacterController).
GameObject player = GameObject.FindPlayer();
// All: every object in the scene.
Debug.Log(GameObject.All().Count + " objects in the scene");
// ---- making objects ----
// Spawn: a primitive ("Cube", "Sphere", "Plane", "Cylinder", "Capsule", "Cone", "Torus", "" for empty)...
GameObject marker = GameObject.Spawn("Sphere");
// ...at a position, or with a position, rotation (degrees) and scale.
GameObject pillar = GameObject.Spawn("Cylinder", new Vector3(3f, 1f, 0f));
GameObject ramp = GameObject.Spawn("Cube", new Vector3(0f, 0.5f, -4f), new Vector3(20f, 0f, 0f), new Vector3(3f, 0.2f, 4f));
// Spawn with a Mesh field: a model from the project.
GameObject oak = GameObject.Spawn(tree, new Vector3(-5f, 0f, -5f));
// Instantiate: a copy of a prefab, from a Prefab field or a project path.
GameObject box = GameObject.Instantiate(crate, new Vector3(1f, 0f, 1f));
GameObject box2 = GameObject.Instantiate("Prefabs/Crate.prefab", new Vector3(2f, 0f, 1f));
// ---- physics for spawned objects ----
// AddRigidbody: a body that falls and is pushed (with a collider that fits). AddCollider: a fixed collider.
marker.AddRigidbody(2f);
ramp.AddCollider();
// rigidbody: the object's physics body.
marker.rigidbody.AddImpulse(Vector3.up * 5f);
// ---- parents and children ----
// SetParent: put an object under another (null: back to the scene root). parent, children: read the tree.
pillar.SetParent(me);
Debug.Log(pillar.parent.name + " now has " + me.children.Count + " children");
// ---- looks ----
// SetColor: tint the surface (1, 1, 1 is no tint). SetMaterial: a material from the project.
marker.SetColor(new Vector3(1f, 0.3f, 0.3f));
pillar.SetMaterial("Materials/Stone.mat");
// SetModelPart: turn one named part of a model (a wheel, a turret) from its resting pose.
oak.SetModelPart("Crown", new Vector3(0f, 15f, 0f));
// ---- components while playing ----
// AddComponent, RemoveComponent: add a component with its usual values, or take one off.
marker.AddComponent("PointLight");
box.RemoveComponent("AudioSource");
// Set: change a field of a component: a number, a true/false, text, or a vector / colour.
marker.Set("PointLight", "intensity", 3f);
marker.Set("PointLight", "cast_shadows", false);
box2.Set("SpriteRenderer", "texture", "Sprites/Crate.png");
marker.Set("PointLight", "color", new Vector3(1f, 0.6f, 0.2f));
// ---- scripts ----
// GetScript / GetComponent: the script of a class on an object (null when it has none).
GameObjectExampleHealth hp = player.GetScript<GameObjectExampleHealth>();
GameObjectExampleHealth same = player.GetComponent<GameObjectExampleHealth>();
if (hp != null && hp == same) hp.Heal(10f);
// GetComponent of a built-in part (null when it has none): Rigidbody, AudioSource, Light, MeshRenderer, Collider, ...
AudioSource sound = me.GetComponent<AudioSource>();
if (sound != null) sound.Play();
// TryGetComponent: the same, saying whether it was there. GetComponents: every script of a class on it.
if (me.TryGetComponent(out Light lamp)) lamp.intensity = 2f;
Debug.Log(me.GetComponents<GameObjectExampleHealth>().Count + " health scripts");
// GetComponentInChildren / GetComponentsInChildren: on it or the objects under it. GetComponentInParent: on it or above.
Collider hitBox = me.GetComponentInChildren<Collider>();
List<MeshRenderer> looks = me.GetComponentsInChildren<MeshRenderer>();
GameObjectExampleHealth owner = me.GetComponentInParent<GameObjectExampleHealth>();
// HasComponent: whether it has a component, by its Inspector name.
if (hitBox != null && me.HasComponent("RigidBody")) Debug.Log(looks.Count + " looks, owned: " + (owner != null));
// FindGameObjectWithTag: the first object with a tag. FindGameObjectsWithTag: all of them, as an array.
GameObject goal = GameObject.FindGameObjectWithTag("Finish");
GameObject[] spawns = GameObject.FindGameObjectsWithTag("Respawn");
// activeSelf: switched on itself. activeInHierarchy: and every object above it is too.
if (goal != null && goal.activeSelf && goal.activeInHierarchy) Debug.Log(spawns.Length + " spawn points");
// SendMessage: call a method by name on every script of an object that has it.
door.SendMessage("Open");
player.SendMessage("TakeDamage", 5f);
// ---- the built-in controllers of an object (null when it has no such component) ----
// animator, agent, character, model.
if (player.animator != null) player.animator.Play();
if (enemies.Count > 0 && enemies[0].agent != null) enemies[0].agent.SetDestination(player.transform.position);
if (player.character != null) player.character.Jump();
if (player.model != null) player.model.Play("Wave");
// ---- on, off and gone ----
// active / SetActive / enabled: switch an object (and what is under it) off and on.
door.active = false;
door.SetActive(true);
marker.enabled = true;
// Destroy: remove an object at the end of the frame. exists: false once it was destroyed.
GameObject.Destroy(box2);
Debug.Log("box2 exists until the end of this frame: " + box2.exists);
}
}
public class GameObjectExampleHealth : Behaviour
{
public float health = 50f;
public void Heal(float amount) { health += amount; }
void TakeDamage(float amount) { health -= amount; }
}
WaitForSeconds
class WaitForSeconds
Yield it from a coroutine to wait this many seconds of game time: yield return new WaitForSeconds(2f);
| Member | Description | Example |
|---|---|---|
WaitForSeconds(float seconds) | Waits this many seconds (game time: stands still while Time.timeScale is 0). | yield return new WaitForSeconds(0.5f); |
Example (WaitForSeconds.cs)
// WaitForSeconds: a pause in a coroutine, in game time.
using System.Collections;
public class WaitForSecondsExample : Behaviour
{
public Prefab enemy;
// A Start that returns IEnumerator runs as a coroutine by itself.
IEnumerator Start()
{
for (int wave = 1; wave <= 5; wave++)
{
UI.SetText("Wave", "Wave " + wave);
for (int i = 0; i < wave * 2; i++)
{
GameObject.Instantiate(enemy, new Vector3(Random.Range(-8f, 8f), 0f, -12f));
// Half a second between enemies (game time: it stands still while Time.timeScale is 0).
yield return new WaitForSeconds(0.5f);
}
// Ten seconds before the next wave.
yield return new WaitForSeconds(10f);
}
}
}
WaitForSecondsRealtime
class WaitForSecondsRealtime
Like WaitForSeconds but real time: it counts on while the game is paused or Time.timeScale is 0.
| Member | Description | Example |
|---|---|---|
WaitForSecondsRealtime(float seconds) | Waits this many real seconds. | yield return new WaitForSecondsRealtime(1f); |
Example (WaitForSecondsRealtime.cs)
// WaitForSecondsRealtime: a pause in a coroutine in real time: it keeps counting while the game is paused.
using System.Collections;
public class WaitForSecondsRealtimeExample : Behaviour
{
public override void Update(float deltaTime)
{
if (Input.GetKeyDown("P")) StartCoroutine(PauseWithCountdown());
}
IEnumerator PauseWithCountdown()
{
Time.timeScale = 0f; // the game stops
for (int n = 3; n > 0; n--)
{
UI.SetText("Countdown", n.ToString());
// WaitForSeconds would never end here (game time stands still); real seconds still pass.
yield return new WaitForSecondsRealtime(1f);
}
UI.SetText("Countdown", "");
Time.timeScale = 1f;
}
}
WaitUntil
class WaitUntil
Yield it from a coroutine to wait until the condition is true (checked once a frame): yield return new WaitUntil(() => door.open);
| Member | Description | Example |
|---|---|---|
WaitUntil(Func<bool> predicate) | Waits until predicate returns true. | yield return new WaitUntil(() => keyTaken); |
Example (WaitUntil.cs)
// WaitUntil: a coroutine waits until something becomes true (checked once a frame).
using System.Collections;
public class WaitUntilExample : Behaviour
{
public GameObject door;
bool keyTaken;
public override void OnTriggerEnter(GameObject other) { keyTaken = true; }
IEnumerator Start()
{
UI.SetText("Hint", "Find the key");
// Goes on once the key has been picked up, however long that takes.
yield return new WaitUntil(() => keyTaken);
UI.SetText("Hint", "The door is open");
Tween.Move(door, door.transform.position + Vector3.up * 3f, 1.5f);
}
}
WaitWhile
class WaitWhile
Yield it from a coroutine to wait as long as the condition stays true (checked once a frame).
| Member | Description | Example |
|---|---|---|
WaitWhile(Func<bool> predicate) | Waits while predicate returns true. | yield return new WaitWhile(() => boss != null && boss.exists); |
Example (WaitWhile.cs)
// WaitWhile: a coroutine waits for as long as something stays true (checked once a frame).
using System.Collections;
public class WaitWhileExample : Behaviour
{
public GameObject boss;
IEnumerator Start()
{
// Wait while the boss is still in the scene.
yield return new WaitWhile(() => boss != null && boss.exists);
UI.SetText("Banner", "Victory");
yield return new WaitForSeconds(3f);
Scene.Next();
}
}
WaitForEndOfFrame
class WaitForEndOfFrame
Yield it from a coroutine to go on in the next frame (the same as yield return null).
Example (WaitForEndOfFrame.cs)
// WaitForEndOfFrame: a coroutine goes on in the next frame (the same as `yield return null`).
using System.Collections;
public class WaitForEndOfFrameExample : Behaviour
{
IEnumerator Start()
{
// Spread heavy work over frames: ten objects a frame instead of a thousand at once.
for (int i = 0; i < 1000; i++)
{
GameObject.Spawn("Cube", new Vector3(i % 40, 0f, -(i / 40)));
if (i % 10 == 9) yield return new WaitForEndOfFrame();
}
Debug.Log("field built");
}
}
Coroutine
class Coroutine
A running coroutine, as StartCoroutine returns it. Yield it from another coroutine to wait until it ends.
| Member | Description | Example |
|---|---|---|
bool done | True once it has run to its end or was stopped. | Debug.Log("arrived; still blinking: " + !blinking.done); |
Example (Coroutine.cs)
// Coroutine: a coroutine that is running: wait for it from another, check it, or stop it.
using System.Collections;
public class CoroutineExample : Behaviour
{
Coroutine blinking;
IEnumerator Start()
{
// StartCoroutine returns the Coroutine.
blinking = StartCoroutine(Blink());
Coroutine walk = StartCoroutine(WalkTo(new Vector3(5f, 0f, 0f)));
// Yielding a Coroutine waits until it ends.
yield return walk;
// done: true once it ran to its end or was stopped.
Debug.Log("arrived; still blinking: " + !blinking.done);
StopCoroutine(blinking);
gameObject.SetActive(true);
}
IEnumerator Blink()
{
while (true)
{
gameObject.SetColor(Color.red);
yield return new WaitForSeconds(0.2f);
gameObject.SetColor(Color.white);
yield return new WaitForSeconds(0.2f);
}
}
IEnumerator WalkTo(Vector3 goal)
{
while (Vector3.Distance(transform.position, goal) > 0.05f)
{
transform.position = Vector3.MoveTowards(transform.position, goal, 2f * Time.deltaTime);
yield return null;
}
}
}
LayerMask
struct LayerMask
A set of layers, one bit per layer: Physics.Raycast(o, d, out hit, 50f, LayerMask.GetMask("Ground", "Walls")). The names are the project's (Project Settings > Tags and Layers); an object's layer is go.layer.
| Member | Description | Example |
|---|---|---|
int value | The bits: layer n is bit n. | int bits = ground.value; |
static implicit operator int(LayerMask m) | A mask as its bits. | int alsoBits = ground; |
static implicit operator LayerMask(int bits) | Bits as a mask. | LayerMask both = solid | (1 << enemies); |
static int NameToLayer(string name) | The index of the layer with this name, or -1. | int enemies = LayerMask.NameToLayer("Enemies"); |
static string LayerToName(int layer) | The name of a layer ("" when it has none). | Debug.Log("layer " + enemies + " is called '" + LayerMask.LayerToName(enemies) + "'"); |
static int GetMask(params string[] layerNames) | The mask of these named layers; a name the project does not have is skipped (with a warning). | int solid = LayerMask.GetMask("Ground", "Walls"); |
Example (LayerMask.cs)
// LayerMask: a set of layers, so a raycast or an overlap check sees only some objects.
public class LayerMaskExample : Behaviour
{
// A public LayerMask shows in the Inspector as a list of the project's layers to tick.
public LayerMask ground;
public override void Start()
{
// NameToLayer: a layer's number by its name (-1 when the project has no such layer). LayerToName: the other way.
int enemies = LayerMask.NameToLayer("Enemies");
Debug.Log("layer " + enemies + " is called '" + LayerMask.LayerToName(enemies) + "'");
// GetMask: the mask of several named layers.
int solid = LayerMask.GetMask("Ground", "Walls");
// value: the bits (layer n is bit n). A mask turns into an int and an int into a mask by themselves.
int bits = ground.value;
int alsoBits = ground;
LayerMask both = solid | (1 << enemies);
Debug.Log("ground mask " + bits + " = " + alsoBits + "; all three: " + both.value);
}
public override void Update(float deltaTime)
{
// Only the ground stops this ray: the player's own body and pickups are ignored.
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 2f, ground))
transform.position = hit.point + Vector3.up;
// The object's own layer is a number 0..31.
if (gameObject.layer == LayerMask.NameToLayer("Enemies")) gameObject.SetColor(Color.red);
}
}
Ray
struct Ray
A line from a point in a direction (Physics.Raycast, Camera.ScreenPointToRay).
| Member | Description | Example |
|---|---|---|
Vector3 origin | Where the ray starts. | Gizmos.DrawRay(sight.origin, sight.direction * 10f); |
Vector3 direction | Which way it goes (kept at length 1). | Gizmos.DrawRay(sight.origin, sight.direction * 10f); |
Ray(Vector3 origin, Vector3 direction) | A ray from origin along direction. | Ray sight = new Ray(transform.position + Vector3.up, transform.forward); |
Vector3 GetPoint(float distance) | The point distance along the ray. | Vector3 hook = sight.GetPoint(5f); |
override string ToString() | The ray as text. | if (Input.GetMouseButtonDown(0)) Debug.Log(pointer.ToString() + " hook at " + hook); |
Example (Ray.cs)
// Ray: a line from a point in a direction.
public class RayExample : Behaviour
{
public override void Update(float deltaTime)
{
// A ray from this object straight ahead (the direction is kept at length 1).
Ray sight = new Ray(transform.position + Vector3.up, transform.forward);
// origin: where it starts. direction: which way it goes.
Gizmos.DrawRay(sight.origin, sight.direction * 10f);
// GetPoint: the point so far along the ray: where a thrown hook would be 5 m out.
Vector3 hook = sight.GetPoint(5f);
// A ray is what Physics.Raycast and Camera.ScreenPointToRay work with.
if (Physics.Raycast(sight, out RaycastHit hit, 10f)) hook = hit.point;
Ray pointer = Camera.ScreenPointToRay(Input.mousePosition);
// ToString: the ray as text.
if (Input.GetMouseButtonDown(0)) Debug.Log(pointer.ToString() + " hook at " + hook);
}
}
Plane
struct Plane
A flat surface without end: a normal and how far it is from the origin along it.
| Member | Description | Example |
|---|---|---|
Vector3 normal | The way the plane faces (length 1). | Debug.Log("water faces " + water.normal + ", distance " + water.distance); |
float distance | The signed distance from the world's origin to the plane along its normal, negated: a floor at height 5 facing up has -5. | Debug.Log("water faces " + water.normal + ", distance " + water.distance); |
Plane(Vector3 inNormal, Vector3 point) | The plane through point facing inNormal. | Plane water = new Plane(Vector3.up, new Vector3(0f, waterLevel, 0f)); |
float GetDistanceToPoint(Vector3 point) | The signed distance of point from the plane (positive on the side it faces). | float height = water.GetDistanceToPoint(transform.position); |
bool GetSide(Vector3 point) | True when point is on the side the plane faces. | bool dry = water.GetSide(transform.position); |
Vector3 ClosestPointOnPlane(Vector3 point) | The point on the plane nearest point. | Vector3 shadow = water.ClosestPointOnPlane(transform.position); |
bool Raycast(Ray ray, out float enter) | Where ray meets the plane: true and the distance along the ray, or false when it runs alongside or away. | if (water.Raycast(pointer, out float enter)) |
Example (Plane.cs)
// Plane: a flat surface without end: the ground, a mirror, a water level.
public class PlaneExample : Behaviour
{
public float waterLevel = 0f;
public override void Update(float deltaTime)
{
// The plane through a point, facing a direction: the water surface, facing up.
Plane water = new Plane(Vector3.up, new Vector3(0f, waterLevel, 0f));
// normal: the way it faces. distance: its signed distance from the world's origin, negated (a floor at height 5 facing up has -5).
Debug.Log("water faces " + water.normal + ", distance " + water.distance);
// GetDistanceToPoint: how far a point is from the plane (positive on the side it faces): how deep we are.
float height = water.GetDistanceToPoint(transform.position);
// GetSide: true on the side the plane faces (above the water).
bool dry = water.GetSide(transform.position);
if (!dry) transform.position += Vector3.up * (-height) * 2f * deltaTime; // float up
// ClosestPointOnPlane: the point of the plane nearest another: where a shadow blob goes.
Vector3 shadow = water.ClosestPointOnPlane(transform.position);
// Raycast: where a ray meets the plane: the point of the water under the pointer.
Ray pointer = Camera.ScreenPointToRay(Input.mousePosition);
if (water.Raycast(pointer, out float enter))
{
Vector3 onWater = pointer.GetPoint(enter);
Gizmos.DrawLine(shadow, onWater);
}
}
}
Bounds
struct Bounds
An axis-aligned box: a centre and half its size each way.
| Member | Description | Example |
|---|---|---|
Vector3 center | The middle of the box. | Debug.Log("zone at " + zone.center + ", half size " + zone.extents + ", size " + zone.size + ", from " + zo... |
Vector3 extents | Half the box's size along each axis. | Debug.Log("zone at " + zone.center + ", half size " + zone.extents + ", size " + zone.size + ", from " + zo... |
Bounds(Vector3 center, Vector3 size) | A box at center of full size size. | zone = new Bounds(transform.position, zoneSize); |
Vector3 size | The box's full size. | Debug.Log("zone at " + zone.center + ", half size " + zone.extents + ", size " + zone.size + ", from " + zo... |
Vector3 min | The corner with the smallest x, y and z. | Debug.Log("zone at " + zone.center + ", half size " + zone.extents + ", size " + zone.size + ", from " + zo... |
Vector3 max | The corner with the largest x, y and z. | Debug.Log("zone at " + zone.center + ", half size " + zone.extents + ", size " + zone.size + ", from " + zo... |
bool Contains(Vector3 point) | True when point is inside the box or on its faces. | UI.SetVisible("SafeZoneBadge", zone.Contains(p)); |
bool Intersects(Bounds other) | True when the two boxes overlap. | if (Input.GetMouseButtonDown(0) && zone.Intersects(blast)) Debug.Log("the blast reaches the zone"); |
void Encapsulate(Vector3 point) | Grows the box to take in point. | foreach (GameObject child in gameObject.children) zone.Encapsulate(child.transform.position); |
Vector3 ClosestPoint(Vector3 point) | The point in or on the box nearest point. | if (!zone.Contains(p)) player.transform.position = zone.ClosestPoint(p); |
bool IntersectRay(Ray ray) | True when ray passes through the box. | if (zone.IntersectRay(Camera.ScreenPointToRay(Input.mousePosition))) Gizmos.DrawWireCube(zone.center, zone.... |
Example (Bounds.cs)
// Bounds: a box lined up with the world axes: zones, camera limits, "is it inside?".
public class BoundsExample : Behaviour
{
public Vector3 zoneSize = new Vector3(10f, 4f, 10f);
Bounds zone;
public override void Start()
{
// A box from its centre and full size.
zone = new Bounds(transform.position, zoneSize);
// center, extents (half the size each way), size, min and max corners.
Debug.Log("zone at " + zone.center + ", half size " + zone.extents + ", size " + zone.size + ", from " + zone.min + " to " + zone.max);
// size can be set too.
zone.size = zoneSize * 1.1f;
// Encapsulate: grow the box to take in a point (the bounds of a whole group of objects).
foreach (GameObject child in gameObject.children) zone.Encapsulate(child.transform.position);
}
public override void Update(float deltaTime)
{
GameObject player = GameObject.FindPlayer();
Vector3 p = player.transform.position;
// Contains: is a point inside the box?
UI.SetVisible("SafeZoneBadge", zone.Contains(p));
// ClosestPoint: the point in or on the box nearest another: keep the player inside the arena.
if (!zone.Contains(p)) player.transform.position = zone.ClosestPoint(p);
// Intersects: do two boxes overlap?
Bounds blast = new Bounds(Input.mouseWorldPosition, Vector3.one * 3f);
if (Input.GetMouseButtonDown(0) && zone.Intersects(blast)) Debug.Log("the blast reaches the zone");
// IntersectRay: does a ray pass through the box?
if (zone.IntersectRay(Camera.ScreenPointToRay(Input.mousePosition))) Gizmos.DrawWireCube(zone.center, zone.size);
}
}
Matrix4x4
struct Matrix4x4
A 4x4 transform matrix (column vectors): move, turn and scale points and directions.
| Member | Description | Example |
|---|---|---|
float[] m | The 16 numbers, row by row (m[row * 4 + column]). | Debug.Log("x offset " + moveX + ", " + place.m.Length + " numbers"); |
static Matrix4x4 identity | The matrix that changes nothing. | Matrix4x4 none = Matrix4x4.identity; |
float this[int row, int column] | The number at row, column. | float moveX = place[0, 3]; |
static Matrix4x4 TRS(Vector3 pos, Quaternion q, Vector3 s) | Moves by pos, turns by q and scales by s (scale first, then turn, then move). | Matrix4x4 place = Matrix4x4.TRS(new Vector3(10f, 0f, 0f), Quaternion.Euler(0f, 90f, 0f), Vector3.one * 2f); |
Vector3 MultiplyPoint(Vector3 p) | A point moved by the whole matrix (turned, scaled and moved). | Vector3 corner = place.MultiplyPoint(new Vector3(1f, 0f, 0f)); |
Vector3 MultiplyVector(Vector3 v) | A direction turned and scaled, but not moved. | Vector3 facing = place.MultiplyVector(Vector3.forward); |
static Matrix4x4 operator *(Matrix4x4 a, Matrix4x4 b) | The two matrices one after the other: b first, then a. | Matrix4x4 childInWorld = place * child; |
Example (Matrix4x4.cs)
// Matrix4x4: a transform as one value: move, turn and scale points and directions by hand.
public class Matrix4x4Example : Behaviour
{
public override void Start()
{
// identity: the matrix that changes nothing.
Matrix4x4 none = Matrix4x4.identity;
// TRS: move by a position, turn by a rotation, scale by a size (scale first, then turn, then move).
Matrix4x4 place = Matrix4x4.TRS(new Vector3(10f, 0f, 0f), Quaternion.Euler(0f, 90f, 0f), Vector3.one * 2f);
// MultiplyPoint: a point through the whole matrix (scaled, turned and moved).
Vector3 corner = place.MultiplyPoint(new Vector3(1f, 0f, 0f));
// MultiplyVector: a direction, turned and scaled but not moved.
Vector3 facing = place.MultiplyVector(Vector3.forward);
Debug.Log("corner " + corner + ", facing " + facing);
// *: two matrices one after the other (the right one first): a child placed in its parent, then in the world.
Matrix4x4 child = Matrix4x4.TRS(new Vector3(0f, 1f, 0f), Quaternion.identity, Vector3.one);
Matrix4x4 childInWorld = place * child * none;
Debug.Log("child origin in the world: " + childInWorld.MultiplyPoint(Vector3.zero));
// The 16 numbers: m is the whole array row by row; [row, column] reads or sets one.
float moveX = place[0, 3];
place[1, 3] = 5f; // lift it 5 up
Debug.Log("x offset " + moveX + ", " + place.m.Length + " numbers");
}
}
Behaviour
class Behaviour
Base class of every script. Public fields appear in the Inspector.
| Member | Description | Example |
|---|---|---|
GameObject gameObject | The object this script is attached to. | public override void Awake() { Debug.Log("Awake on " + gameObject.name); } |
Transform transform | The transform of the object this script is on. | transform.position = new Vector3(0f, 1f, 0f); |
bool enabled | Disabled scripts do not run Update. | if (Input.GetKeyDown("K")) enabled = false; |
string name | The name of the object this script is on. | public override void Awake() { Debug.Log("Awake on " + gameObject.name); } |
string tag | The tag of the object this script is on. | if (CompareTag("Player")) Debug.Log(name + " is the player, tagged " + tag); |
bool CompareTag(string t) | True when the object this script is on has this tag. | if (CompareTag("Player")) Debug.Log(name + " is the player, tagged " + tag); |
T GetComponent<T>() where T : class | A part of this script's object, or null: another script, Rigidbody, AudioSource, Light, ... (see GameObject.GetComponent). | Rigidbody body = GetComponent<Rigidbody>(); |
bool TryGetComponent<T>(out T component) where T : class | True when this script's object has that part, and it in component. | if (TryGetComponent(out AudioSource sound)) sound.Play(); |
List<T> GetComponents<T>() where T : class | Every such part on this script's object. | Debug.Log(GetComponents<BehaviourExample>().Count + " of these, " + GetComponentsInChildren<Light>().Count ... |
T GetComponentInChildren<T>(bool includeInactive = false) where T : class | The part on this script's object or the first object under it that has one. | Light lamp = GetComponentInChildren<Light>(); |
List<T> GetComponentsInChildren<T>(bool includeInactive = false) where T : class | That part on this script's object and every object under it. | Debug.Log(GetComponents<BehaviourExample>().Count + " of these, " + GetComponentsInChildren<Light>().Count ... |
T GetComponentInParent<T>() where T : class | The part on this script's object or the nearest object above it that has one. | BehaviourExample above = GetComponentInParent<BehaviourExample>(); |
static void Destroy(GameObject go) | Removes an object (and its scripts) at the end of the frame: Destroy(other). | Destroy(s, 2f); |
void Destroy(GameObject go, float seconds) | Removes an object after seconds of game time. | Destroy(s, 2f); |
static GameObject Instantiate(Prefab prefab, Vector3 position) | Makes a copy of a prefab field at a place: Instantiate(bullet, transform.position). | GameObject s = Instantiate(spark, transform.position); |
static T FindObjectOfType<T>() where T : Behaviour | The first script of type T in the scene, or null. | BehaviourExample first = FindObjectOfType<BehaviourExample>(); |
static List<T> FindObjectsOfType<T>() where T : Behaviour | Every script of type T in the scene. | Debug.Log(FindObjectsOfType<BehaviourExample>().Count + " in the scene; first is me: " + (first == this) + ... |
virtual void Awake() | Called once when the object comes into the game, before every Start. | public override void Awake() { Debug.Log("Awake on " + gameObject.name); } |
virtual void Start() | Called once, before the first Update. | public override void Start() |
virtual void FixedUpdate() | Called at a steady 50 times a second of game time, however fast frames come (use Time.fixedDeltaTime). | public override void FixedUpdate() { gameObject.rigidbody.AddForce(Vector3.up * 0.1f); } |
virtual void LateUpdate() | Called every frame after every Update (a camera that follows what Update moved). | public override void LateUpdate() { transform.LookAt(Vector3.zero); } |
virtual void OnDestroy() | Called when the object is destroyed or leaves the game with its scene. | public override void OnDestroy() { Debug.Log(gameObject.name + " is gone"); } |
virtual void Update(float deltaTime) | Called every frame; deltaTime is in seconds. | public override void Update(float deltaTime) |
virtual void OnCollisionEnter(GameObject other) | Another object's box started overlapping this one's. | public override void OnCollisionEnter(GameObject other) { Debug.Log("bumped " + other.name); } |
virtual void OnCollisionStay(GameObject other) | Called every frame while other keeps touching this object (after OnCollisionEnter). | public override void OnCollisionStay(GameObject other) { gameObject.SetColor(Color.red); } |
virtual void OnCollisionExit(GameObject other) | The overlap with other ended. | public override void OnCollisionExit(GameObject other) { gameObject.SetColor(Color.white); } |
virtual void OnTriggerEnter(GameObject other) | Another object entered this object's trigger zone (Trigger3D), or this object entered one. | public override void OnTriggerEnter(GameObject other) { Debug.Log(other.name + " entered the zone"); } |
virtual void OnTriggerStay(GameObject other) | Called every frame while other stays inside the trigger zone (after OnTriggerEnter). | public override void OnTriggerStay(GameObject other) { other.SendMessage("TakeDamage", Time.deltaTime); } |
virtual void OnTriggerExit(GameObject other) | The other object left the trigger zone. | public override void OnTriggerExit(GameObject other) { Debug.Log(other.name + " left the zone"); } |
virtual void OnEnable() | Called when the script becomes live: after Awake, and whenever it or its object is switched back on. | public override void OnEnable() { pulse = StartCoroutine(Pulse()); } |
virtual void OnDisable() | Called when the script stops being live: switched off, its object deactivated, or before OnDestroy. | public override void OnDisable() { StopPulsing(); } |
virtual void OnMouseEnter() | The mouse pointer moved onto this object (3D objects with a mesh). | public override void OnMouseEnter() { transform.scale = Vector3.one * 1.1f; } |
virtual void OnMouseExit() | The mouse pointer left this object. | public override void OnMouseExit() { transform.scale = Vector3.one; } |
virtual void OnMouseOver() | Every frame the pointer is over this object. | public override void OnMouseOver() { transform.Rotate(new Vector3(0f, 90f * Time.deltaTime, 0f)); } |
virtual void OnMouseDown() | The left button went down over this object. | public override void OnMouseDown() { Debug.Log("grabbed"); } |
virtual void OnMouseDrag() | Every frame the left button is held after pressing it on this object, wherever the pointer is. | public override void OnMouseDrag() { transform.position = Input.mouseWorldPosition; } |
virtual void OnMouseUp() | The left button was released after being pressed on this object. | public override void OnMouseUp() { Debug.Log("dropped"); } |
virtual void OnMouseUpAsButton() | The left button was pressed and released over this same object: a click. | public override void OnMouseUpAsButton() { Debug.Log("clicked"); } |
virtual void OnDrawGizmos() | Draws with Gizmos in the Scene view, in the editor and while playing (never in the game). | public override void OnDrawGizmos() { Gizmos.DrawWireSphere(transform.position, 0.5f); } |
virtual void OnDrawGizmosSelected() | As OnDrawGizmos, while this object is selected. | public override void OnDrawGizmosSelected() { Gizmos.DrawRay(transform.position, transform.forward * speed); } |
virtual void OnSceneGUI() | Editor only, while this object is the selected one: draw Handles the user can drag (range = Handles.Slider(...)) and change this script's fields or the object's transform from them. A whole drag is one undo step. | public override void OnSceneGUI() { speed = Handles.Slider(transform.position + transform.forward * speed, ... |
Coroutine StartCoroutine(IEnumerator routine) | Starts a coroutine: a method returning IEnumerator that runs over several frames, waiting with yield return null (the next frame), new WaitForSeconds(s), new WaitUntil(() => ...), new WaitWhile(...), another coroutine or a Tween. It runs at once up to its first yield, then after Update each frame; it stops when it ends, by StopCoroutine, or when its object is destroyed or switched off. IEnumerator Start() runs as a coroutine by itself. | public override void OnEnable() { pulse = StartCoroutine(Pulse()); } |
void StopCoroutine(Coroutine routine) | Stops a coroutine this script started. | StopCoroutine(blink); |
void StopCoroutine(IEnumerator routine) | Stops the coroutine this script started from that IEnumerator. | StopCoroutine(blink); |
void StopAllCoroutines() | Stops every coroutine this script started. | StopAllCoroutines(); |
Example (Behaviour.cs)
// Behaviour: the base class of every script: when each method is called.
using System.Collections;
public class BehaviourExample : Behaviour
{
public float speed = 2f; // public fields show in the Inspector
Coroutine pulse;
// ---- start-up, in this order ----
// Awake: once, when the object comes into the game, before every Start.
public override void Awake() { Debug.Log("Awake on " + gameObject.name); }
// OnEnable: when the script becomes live: after Awake, and whenever it or its object is switched back on.
public override void OnEnable() { pulse = StartCoroutine(Pulse()); }
// Start: once, before the first Update.
public override void Start()
{
transform.position = new Vector3(0f, 1f, 0f);
// name, tag, CompareTag: the object's, without "gameObject." in front.
if (CompareTag("Player")) Debug.Log(name + " is the player, tagged " + tag);
// GetComponent and its kin: parts of this script's object (see GameObject.GetComponent).
Rigidbody body = GetComponent<Rigidbody>();
if (TryGetComponent(out AudioSource sound)) sound.Play();
Debug.Log(GetComponents<BehaviourExample>().Count + " of these, " + GetComponentsInChildren<Light>().Count + " lights under it");
Light lamp = GetComponentInChildren<Light>();
BehaviourExample above = GetComponentInParent<BehaviourExample>();
// FindObjectOfType / FindObjectsOfType: the scripts of a class anywhere in the scene.
BehaviourExample first = FindObjectOfType<BehaviourExample>();
Debug.Log(FindObjectsOfType<BehaviourExample>().Count + " in the scene; first is me: " + (first == this) + (body != null) + (lamp != null) + (above != null));
}
// Instantiate and Destroy, without "GameObject." in front: a copy of a prefab field, and an object taken away (now, or
// after some seconds).
public Prefab spark;
void Burst()
{
GameObject s = Instantiate(spark, transform.position);
Destroy(s, 2f);
GameObject old = GameObject.Find("Old");
if (old != null) Destroy(old);
}
// ---- every frame ----
// Update: every frame; deltaTime is the seconds since the last one.
public override void Update(float deltaTime)
{
transform.Translate(transform.forward * speed * deltaTime);
// enabled: false stops this script's Update (and calls OnDisable).
if (Input.GetKeyDown("K")) enabled = false;
}
// FixedUpdate: 50 times a second of game time, whatever the frame rate: forces and physics.
public override void FixedUpdate() { gameObject.rigidbody.AddForce(Vector3.up * 0.1f); }
// LateUpdate: every frame after every Update: a camera that follows what Update moved.
public override void LateUpdate() { transform.LookAt(Vector3.zero); }
// ---- touching other objects ----
// OnCollisionEnter / Stay / Exit: another object starts touching, keeps touching (every frame), stops touching.
public override void OnCollisionEnter(GameObject other) { Debug.Log("bumped " + other.name); }
public override void OnCollisionStay(GameObject other) { gameObject.SetColor(Color.red); }
public override void OnCollisionExit(GameObject other) { gameObject.SetColor(Color.white); }
// OnTriggerEnter / Stay / Exit: the same for a trigger zone, which nothing bumps into.
public override void OnTriggerEnter(GameObject other) { Debug.Log(other.name + " entered the zone"); }
public override void OnTriggerStay(GameObject other) { other.SendMessage("TakeDamage", Time.deltaTime); }
public override void OnTriggerExit(GameObject other) { Debug.Log(other.name + " left the zone"); }
// ---- the pointer on this object ----
// OnMouseEnter / Exit: the pointer moves onto or off the object. OnMouseOver: every frame it is over it.
public override void OnMouseEnter() { transform.scale = Vector3.one * 1.1f; }
public override void OnMouseOver() { transform.Rotate(new Vector3(0f, 90f * Time.deltaTime, 0f)); }
public override void OnMouseExit() { transform.scale = Vector3.one; }
// OnMouseDown / Drag / Up: the left button goes down on it, is held (wherever the pointer goes), comes up.
public override void OnMouseDown() { Debug.Log("grabbed"); }
public override void OnMouseDrag() { transform.position = Input.mouseWorldPosition; }
public override void OnMouseUp() { Debug.Log("dropped"); }
// OnMouseUpAsButton: pressed and released over the same object: a click.
public override void OnMouseUpAsButton() { Debug.Log("clicked"); }
// ---- drawing in the editor's Scene view ----
// OnDrawGizmos: always. OnDrawGizmosSelected: while the object is selected. OnSceneGUI: draggable handles while selected.
public override void OnDrawGizmos() { Gizmos.DrawWireSphere(transform.position, 0.5f); }
public override void OnDrawGizmosSelected() { Gizmos.DrawRay(transform.position, transform.forward * speed); }
public override void OnSceneGUI() { speed = Handles.Slider(transform.position + transform.forward * speed, transform.forward).z; }
// ---- coroutines: methods that run over several frames ----
IEnumerator Pulse()
{
while (true)
{
transform.scale = Vector3.one * (1f + 0.1f * Mathf.Sin(Time.time * 4f));
yield return null; // go on next frame
}
}
void StopPulsing()
{
// StopCoroutine: stop one by its Coroutine, or by the IEnumerator it was started from. StopAllCoroutines: every one.
IEnumerator blink = Pulse();
StartCoroutine(blink);
StopCoroutine(blink);
StopCoroutine(pulse);
StopAllCoroutines();
}
// ---- the end ----
// OnDisable: the script stops being live: switched off, its object deactivated, or just before OnDestroy.
public override void OnDisable() { StopPulsing(); }
// OnDestroy: the object is destroyed or leaves the game with its scene.
public override void OnDestroy() { Debug.Log(gameObject.name + " is gone"); }
}
XR
static class XR
Virtual reality: a game built as a VR headset game (Player options, Android) opens in a Pico or a Quest, drawn for each eye as the head moves, with hand controllers; with a VR Camera on the main camera, a phone in a headset shows both eyes side by side and turns the view as the head turns. This is where the head is and looks, the headset's button, and the hands.
| Member | Description | Example |
|---|---|---|
static bool enabled | True while the game is drawn for a headset: a VR headset, or a VR Camera on the main camera (on a phone or in the editor's Play). | if (!XR.enabled) return; |
static Vector3 headPosition | Where the head is: the main camera's place. | Debug.Log("picked " + looked.name + " looking " + XR.headForward + " from " + XR.headPosition); |
static Vector3 headForward | The way the head looks (a unit vector). | Debug.Log("picked " + looked.name + " looking " + XR.headForward + " from " + XR.headPosition); |
static float headYaw | How far the head has turned since the game began (or since Recenter), in degrees: left is positive. | if (Mathf.Abs(XR.headYaw) > 150f) XR.Recenter(); |
static float headPitch | How far up (positive) or down the head looks, in degrees from level. | if (XR.trigger && XR.headPitch < -60f) Debug.Log("menu (eyes " + XR.eyeDistance + " m apart)"); |
static float eyeDistance | Metres between the eyes. | if (XR.trigger && XR.headPitch < -60f) Debug.Log("menu (eyes " + XR.eyeDistance + " m apart)"); |
static bool trigger | The headset's button is held: a finger on the screen (a Cardboard's lever taps it), or the left mouse button. | if (XR.trigger && XR.headPitch < -60f) Debug.Log("menu (eyes " + XR.eyeDistance + " m apart)"); |
static bool triggerDown | True on the frame the headset's button was pressed. | if (looked != null && XR.triggerDown) |
static GameObject Gaze(float maxDistance = 100f) | The object the player looks at, within maxDistance metres (null when none). | GameObject looked = XR.Gaze(20f); |
static void Recenter() | Makes the way the head looks now straight ahead. | if (Mathf.Abs(XR.headYaw) > 150f) XR.Recenter(); |
static bool headset | True in a real VR headset (a Pico or a Quest, through OpenXR), which tracks the head and has hand controllers; false on a phone in a headset or in the editor. | if (XR.headset && XR.rightHand.tracked && XR.leftHand.tracked) |
static XRHand leftHand | The headset's left hand controller (in a phone headset or the editor it is never tracked). | if (XR.headset && XR.rightHand.tracked && XR.leftHand.tracked) |
static XRHand rightHand | The headset's right hand controller. | if (XR.headset && XR.rightHand.tracked && XR.leftHand.tracked) |
Example (XR.cs)
// XR: virtual reality. Put a VR Camera component on the main camera; while the game plays it is drawn once for each eye and
// the view turns as the head turns (in the editor: hold the right mouse button and move). A game built for a VR headset
// (Player options: Android, "A VR headset game") opens in a Pico or a Quest, with its hand controllers.
public class XRExample : Behaviour
{
public override void Update(float deltaTime)
{
if (!XR.enabled) return;
// what the player looks at; the headset's button (a tap on the screen) picks it up
GameObject looked = XR.Gaze(20f);
if (looked != null && XR.triggerDown)
{
Debug.Log("picked " + looked.name + " looking " + XR.headForward + " from " + XR.headPosition);
looked.SetActive(false);
}
// held down while looking at the floor: a menu, say
if (XR.trigger && XR.headPitch < -60f) Debug.Log("menu (eyes " + XR.eyeDistance + " m apart)");
// turned right round: make where the head looks now straight ahead
if (Mathf.Abs(XR.headYaw) > 150f) XR.Recenter();
// a real headset has hands: the right one points, the left one's stick is read as the gamepad's too
if (XR.headset && XR.rightHand.tracked && XR.leftHand.tracked)
Debug.Log("right hand at " + XR.rightHand.position + ", left stick " + XR.leftHand.stick);
}
}
XRHand
class XRHand
A VR headset's hand controller: XR.leftHand and XR.rightHand. The controllers also work as a gamepad: the left stick moves, the right one turns, the triggers and A B X Y are the gamepad's.
| Member | Description | Example |
|---|---|---|
bool tracked | The controller is on and the headset sees it. | if (!hand.tracked) return; |
Vector3 position | Where the controller is in the world. | if (hand.trigger > 0.1f) Debug.Log("aiming from " + hand.position + " along " + hand.forward); |
Vector3 forward | Which way it points (a unit vector). | if (hand.trigger > 0.1f) Debug.Log("aiming from " + hand.position + " along " + hand.forward); |
float trigger | How far the trigger is pulled, 0 to 1. | if (hand.trigger > 0.1f) Debug.Log("aiming from " + hand.position + " along " + hand.forward); |
bool triggerDown | True on the frame the trigger was pulled past half way. | if (target != null && hand.triggerDown) target.SetActive(false); |
float grip | How hard the grip is squeezed, 0 to 1. | float reach = hand.grip > 0.5f ? 60f : 15f; |
Vector2 stick | The thumbstick, -1 to 1 each way (right and up are positive). | if (hand.stick.x > 0.8f && hand.stickPressed) Debug.Log("stick pushed right and pressed"); |
bool stickPressed | The thumbstick is pressed in. | if (hand.stick.x > 0.8f && hand.stickPressed) Debug.Log("stick pushed right and pressed"); |
bool primaryButton | A on the right controller, X on the left. | if (hand.primaryButton) Debug.Log("A"); |
bool secondaryButton | B on the right controller, Y on the left. | if (hand.secondaryButton) Debug.Log("B"); |
bool menuButton | The menu button. | if (XR.leftHand.menuButton) XR.Recenter(); |
GameObject Pointed(float maxDistance = 100f) | The object the controller points at, within maxDistance metres (null when none). | GameObject target = hand.Pointed(reach); |
Example (XRHand.cs)
// XRHand: one of a VR headset's hand controllers (XR.leftHand, XR.rightHand). This one is a laser pointer: pull the trigger
// at something to knock it out of the scene, squeeze the grip to throw a ray further.
public class XRHandExample : Behaviour
{
public override void Update(float deltaTime)
{
XRHand hand = XR.rightHand;
if (!hand.tracked) return;
float reach = hand.grip > 0.5f ? 60f : 15f;
GameObject target = hand.Pointed(reach);
if (target != null && hand.triggerDown) target.SetActive(false);
if (hand.trigger > 0.1f) Debug.Log("aiming from " + hand.position + " along " + hand.forward);
// the stick and the buttons
if (hand.stick.x > 0.8f && hand.stickPressed) Debug.Log("stick pushed right and pressed");
if (hand.primaryButton) Debug.Log("A");
if (hand.secondaryButton) Debug.Log("B");
if (XR.leftHand.menuButton) XR.Recenter();
}
}
RaycastHit
struct RaycastHit
What a raycast hit.
| Member | Description | Example |
|---|---|---|
GameObject gameObject | The object that was hit. | Debug.Log("hit " + hit.gameObject.name + " at height " + hit.transform.position.y); |
Vector3 point | The world point of the hit. | GameObject mark = GameObject.Instantiate(bulletHole, hit.point + hit.normal * 0.01f); |
float distance | Distance from the ray origin. | float falloff = Mathf.Clamp01(1f - hit.distance / 100f); |
Vector3 normal | Which way the surface faces where the ray went in (the side of the object's box it hit). | GameObject mark = GameObject.Instantiate(bulletHole, hit.point + hit.normal * 0.01f); |
Transform transform | The transform of the object that was hit. | if (!Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, 100f)) return; |
Example (RaycastHit.cs)
// RaycastHit: what a raycast found: the object, the point, how far, and which way the surface faces.
public class RaycastHitExample : Behaviour
{
public Prefab bulletHole;
public override void Update(float deltaTime)
{
if (!Input.GetAction("Fire")) return;
if (!Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, 100f)) return;
// gameObject: the object that was hit. transform: its transform.
Debug.Log("hit " + hit.gameObject.name + " at height " + hit.transform.position.y);
// distance: how far along the ray. point: the world point of the hit.
float falloff = Mathf.Clamp01(1f - hit.distance / 100f);
// normal: which way the surface faces at the hit: a mark sits flat on it, a spark bounces off along it.
GameObject mark = GameObject.Instantiate(bulletHole, hit.point + hit.normal * 0.01f);
mark.transform.rotation = Quaternion.LookRotation(-hit.normal);
hit.gameObject.SendMessage("TakeDamage", 25f * falloff);
}
}
Physics
static class Physics
Spatial queries against the scene's objects. Shapes are the objects' bounding boxes (Cube, Sphere, ... use the primitive's box).
| Member | Description | Example |
|---|---|---|
const int AllLayers | Every layer. | bool anything = Physics.Raycast(transform.position, Vector3.up, 50f, Physics.AllLayers); |
const int DefaultRaycastLayers | What a raycast hits when no mask is given: every layer but "Ignore Raycast" (layer 2). | bool blocked = Physics.Raycast(transform.position, toPlayer, toPlayer.Length, Physics.DefaultRaycastLayers); |
static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hit, | Casts a ray and reports the nearest object it hits (objects on the "Ignore Raycast" layer are skipped). An object with a collider is tested by its collider (a sphere as a ball, a capsule by its box); one without, by its mesh's box; a terrain by its ground. | if (Physics.Raycast(transform.position, transform.forward, out RaycastHit ahead, 3f, gameObject)) |
static bool Raycast(Ray ray, out RaycastHit hit, float maxDistance = float.MaxValue, int layerMask = DefaultRaycastLayers) | Casts ray (from Camera.ScreenPointToRay, say) and reports the nearest object it hits. | if (Physics.Raycast(transform.position, transform.forward, out RaycastHit ahead, 3f, gameObject)) |
static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hit, float maxDistance, int layerMask, GameObject ignore = null) | Casts a ray that hits only objects on the layers of layerMask (e.g. LayerMask.GetMask("Ground")) and reports the nearest. | if (Physics.Raycast(transform.position, transform.forward, out RaycastHit ahead, 3f, gameObject)) |
static List<RaycastHit> RaycastAll(Vector3 origin, Vector3 direction, float maxDistance = float.MaxValue, int layerMask = DefaultRaycastLayers, GameObject ignore = null) | Everything a ray passes through, nearest first: a bullet that goes through crates, a laser that counts what it crosses. Each hit is where the ray enters that object. | foreach (RaycastHit crossed in Physics.RaycastAll(transform.position, transform.forward, 40f, Physics.Defau... |
static bool Linecast(Vector3 start, Vector3 end, out RaycastHit hit, int layerMask = DefaultRaycastLayers, GameObject ignore = null) | True when something stands between two points (a wall between a guard and the player), with the first thing in the way in hit. | if (Physics.Linecast(transform.position, player.transform.position, out RaycastHit cover, Physics.DefaultRa... |
static bool Linecast(Vector3 start, Vector3 end, int layerMask = DefaultRaycastLayers) | True when something stands between two points. | if (Physics.Linecast(transform.position, player.transform.position, out RaycastHit cover, Physics.DefaultRa... |
static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hit, float maxDistance = float.MaxValue, int layerMask = DefaultRaycastLayers, GameObject ignore = null) | A ray as thick as a ball of radius: what a rolling ball or a wide projectile would hit first. The hit point is where the ball's centre is when it touches (objects are tested as their boxes grown by the radius). | if (Physics.SphereCast(transform.position, 0.25f, transform.forward, out RaycastHit bump, 10f)) |
static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = float.MaxValue, int layerMask = DefaultRaycastLayers) | True when a ray hits anything on the layers of layerMask within maxDistance (every layer but "Ignore Raycast" when left out). | if (Physics.Raycast(transform.position, transform.forward, out RaycastHit ahead, 3f, gameObject)) |
static List<GameObject> OverlapSphere(Vector3 center, float radius, GameObject ignore = null) | Every object whose box comes within radius of the point. | foreach (GameObject near in Physics.OverlapSphere(transform.position, blastRadius, gameObject)) |
static List<GameObject> OverlapSphere(Vector3 center, float radius, int layerMask, GameObject ignore = null) | Every object on the layers of layerMask whose box comes within radius of the point. | foreach (GameObject near in Physics.OverlapSphere(transform.position, blastRadius, gameObject)) |
static bool CheckSphere(Vector3 center, float radius, int layerMask = AllLayers, GameObject ignore = null) | True when anything is within radius of the point: is there room to spawn here, is the player standing on something. | if (Physics.CheckSphere(spot, 0.6f, Physics.AllLayers, gameObject)) { Debug.Log("no room there"); return; } |
static List<GameObject> OverlapBox(Vector3 center, Vector3 halfExtents, int layerMask = AllLayers, GameObject ignore = null) | Every object whose bounds reach into a box that stands straight in the world, halfExtents from its centre each way: everything in a room, on a pressure plate, inside a blast. | var onThePlate = Physics.OverlapBox(spot, new Vector3(1f, 0.5f, 1f), Physics.AllLayers, crate); |
static Vector3 ClosestPoint(Vector3 point, GameObject gameObject) | The point of an object's box (its collider's, or its mesh's) nearest to point; the point itself when it is inside. How far something is from a wall, where to put a spark. | Vector3 nearest = Physics.ClosestPoint(transform.position, crate); |
Example (Physics.cs)
// Physics: asking the scene questions: what is in this direction, what is near this point.
public class PhysicsExample : Behaviour
{
public float blastRadius = 6f;
public override void Update(float deltaTime)
{
// Raycast with a hit: the nearest object along a ray (up to a distance; an object to ignore: this one).
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit ahead, 3f, gameObject))
Debug.Log("wall " + ahead.distance + " m ahead: " + ahead.gameObject.name);
// Raycast with a layer mask: only the named layers count.
int ground = LayerMask.GetMask("Ground");
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit floor, 1.1f, ground, gameObject))
transform.position = floor.point + Vector3.up;
// Raycast without a hit: just "is anything there?" (a line of sight check). DefaultRaycastLayers is every
// layer but "Ignore Raycast"; AllLayers is every layer.
GameObject player = GameObject.FindPlayer();
Vector3 toPlayer = player.transform.position - transform.position;
bool blocked = Physics.Raycast(transform.position, toPlayer, toPlayer.Length, Physics.DefaultRaycastLayers);
bool anything = Physics.Raycast(transform.position, Vector3.up, 50f, Physics.AllLayers);
if (!blocked && !anything) Debug.Log("the player is in the open and in sight");
// Raycast with a Ray: what is under the pointer.
Ray pointer = Camera.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0) && Physics.Raycast(pointer, out RaycastHit clicked, 200f))
Debug.Log("clicked " + clicked.gameObject.name);
if (Input.GetKeyDown("X")) Explode();
if (Input.GetKeyDown("L")) Laser();
if (Input.GetKeyDown("P")) Place();
}
void Laser()
{
// RaycastAll: everything the ray passes through, nearest first (a beam that goes through crates).
foreach (RaycastHit crossed in Physics.RaycastAll(transform.position, transform.forward, 40f, Physics.DefaultRaycastLayers, gameObject))
Debug.Log("the beam crosses " + crossed.gameObject.name + " at " + crossed.distance + " m");
// Linecast: is anything between two points? With a hit, the first thing in the way.
GameObject player = GameObject.FindPlayer();
if (Physics.Linecast(transform.position, player.transform.position, out RaycastHit cover, Physics.DefaultRaycastLayers, gameObject))
Debug.Log(cover.gameObject == player ? "a clear shot" : "the player is behind " + cover.gameObject.name);
if (!Physics.Linecast(transform.position + Vector3.up * 2f, player.transform.position + Vector3.up * 2f))
Debug.Log("nothing between the two heads");
// SphereCast: a ray as thick as a ball: what a rolling ball half a metre wide would hit first.
if (Physics.SphereCast(transform.position, 0.25f, transform.forward, out RaycastHit bump, 10f))
Debug.Log("the ball would stop " + bump.distance + " m ahead, against " + bump.gameObject.name);
}
void Place()
{
Vector3 spot = transform.position + transform.forward * 2f;
// CheckSphere: is anything within a radius of a point? (is there room to put a crate down)
if (Physics.CheckSphere(spot, 0.6f, Physics.AllLayers, gameObject)) { Debug.Log("no room there"); return; }
GameObject crate = GameObject.Spawn("Cube", spot);
// OverlapBox: every object whose bounds reach into a box (here: 2 x 1 x 2 metres on the floor in front).
var onThePlate = Physics.OverlapBox(spot, new Vector3(1f, 0.5f, 1f), Physics.AllLayers, crate);
Debug.Log(onThePlate.Count + " thing(s) stand on the plate beside the new crate");
// ClosestPoint: the point of an object's box nearest to a point (how far the crate is from this object).
Vector3 nearest = Physics.ClosestPoint(transform.position, crate);
Debug.Log("the crate's nearest corner is " + Vector3.Distance(transform.position, nearest) + " m away");
}
void Explode()
{
// OverlapSphere: every object within a radius of a point (ignoring this one).
foreach (GameObject near in Physics.OverlapSphere(transform.position, blastRadius, gameObject))
{
Vector3 away = (near.transform.position - transform.position).Normalized;
if (near.rigidbody.exists) near.rigidbody.AddImpulse(away * 8f + Vector3.up * 3f);
}
// OverlapSphere with a layer mask: only enemies.
foreach (GameObject enemy in Physics.OverlapSphere(transform.position, blastRadius, LayerMask.GetMask("Enemies"), gameObject))
enemy.SendMessage("TakeDamage", 50f);
Camera.Shake(0.5f, 0.5f);
}
}
Rigidbody
class Rigidbody
The physics body of an object: read its velocity, set it, push it. Objects with a RigidBody component (and those given one by AddRigidbody) are simulated; exists says whether this one is.
| Member | Description | Example |
|---|---|---|
bool exists | True when the object has a moving physics body. | if (!gameObject.rigidbody.exists) Debug.LogWarning(gameObject.name + " has no RigidBody: add one in the Ins... |
Vector3 velocity | How fast it moves, in metres per second. Setting it changes its motion at once. | if (body.velocity.Length > 20f) body.velocity = body.velocity.Normalized * 20f; |
void AddImpulse(Vector3 impulse) | An instant push: the body's momentum changes by this much (a jump, a kick, a bullet hit). | if (Input.GetActionDown("Jump")) body.AddImpulse(Vector3.up * jump); |
void AddForce(Vector3 force) | A push that lasts: call it every frame for as long as the force acts (an engine, wind). | body.AddForce(transform.forward * thrust * Input.GetAxis("Vertical")); |
Example (Rigidbody.cs)
// Rigidbody: the physics body of an object: read its speed, set it, push it.
public class RigidbodyExample : Behaviour
{
public float thrust = 12f;
public float jump = 6f;
public override void Start()
{
// exists: true when the object has a moving physics body (a RigidBody component, or AddRigidbody on a spawned one).
if (!gameObject.rigidbody.exists) Debug.LogWarning(gameObject.name + " has no RigidBody: add one in the Inspector");
}
public override void FixedUpdate()
{
Rigidbody body = gameObject.rigidbody;
// AddForce: a push that lasts: call it every physics step while it acts (an engine, wind).
body.AddForce(transform.forward * thrust * Input.GetAxis("Vertical"));
// AddImpulse: an instant push (a jump, a kick, an explosion).
if (Input.GetActionDown("Jump")) body.AddImpulse(Vector3.up * jump);
// velocity: how fast it moves in metres per second; setting it changes the motion at once.
if (body.velocity.Length > 20f) body.velocity = body.velocity.Normalized * 20f; // a top speed
if (Input.GetKey("Space") && Input.GetKey("Shift")) body.velocity = Vector3.zero; // full stop
}
}
Animator
class Animator
Controls the object's animation clip (the Animator component).
| Member | Description | Example |
|---|---|---|
string state | The state machine's current state ("" without a controller). | if (a.IsInState("Jump")) Debug.Log("in the air (state " + a.state + ")"); |
bool IsInState(string name) | True while the state machine is in the named state. | if (a.IsInState("Jump")) Debug.Log("in the air (state " + a.state + ")"); |
void SetFloat(string name, float value) | Sets a float parameter of the animator controller. | a.SetFloat("speed", Mathf.Abs(move) * walkSpeed); |
void SetBool(string name, bool value) | Sets a bool parameter of the animator controller. | a.SetBool("crouching", Input.GetKey("C")); |
void SetTrigger(string name) | Fires a trigger: the next transition that tests it uses it up. | if (Input.GetActionDown("Jump")) a.SetTrigger("jump"); |
string clip | Project path of the clip, e.g. "Animations/Door.anim". | Debug.Log("this object plays " + a.clip); |
bool playing | True while an animation is playing. | if (a.playing && a.time > 2f) a.time = 0.5f; |
float speed | Playback speed multiplier (1 = normal, negative plays backwards). | a.SetFloat("speed", Mathf.Abs(move) * walkSpeed); |
float time | Seconds into the clip. | if (a.playing && a.time > 2f) a.time = 0.5f; |
void Play(string clipPath = null) | Starts (or resumes) playing; with a path, switches clip and restarts. | a.Play("Animations/Idle.anim"); |
void Stop() | Pauses at the current time. | if (Input.GetKeyDown("O")) a.Stop(); |
void Rewind() | Jumps back to the start. | if (Input.GetKeyDown("R")) a.Rewind(); |
Example (Animator.cs)
// Animator: an object's animation clip and its state machine (the Animator component).
public class AnimatorExample : Behaviour
{
public float walkSpeed = 3f;
public override void Start()
{
Animator a = gameObject.animator;
// clip: the project path of the clip it plays. Play with a path switches clip and starts it.
Debug.Log("this object plays " + a.clip);
a.Play("Animations/Idle.anim");
}
public override void Update(float deltaTime)
{
Animator a = gameObject.animator;
float move = Input.GetAxis("Vertical");
// With an animator controller: SetFloat, SetBool and SetTrigger set its parameters; its transitions do the rest.
a.SetFloat("speed", Mathf.Abs(move) * walkSpeed);
a.SetBool("crouching", Input.GetKey("C"));
if (Input.GetActionDown("Jump")) a.SetTrigger("jump");
// state: the state machine's current state. IsInState: is it in the named one?
if (a.IsInState("Jump")) Debug.Log("in the air (state " + a.state + ")");
// Without a controller, drive the one clip by hand:
// speed: playback speed (1 normal, 2 twice as fast, negative backwards).
a.speed = Input.GetKey("Shift") ? 2f : 1f;
// Stop: pause where it is. Play: go on. Rewind: back to the start.
if (Input.GetKeyDown("O")) a.Stop();
if (Input.GetKeyDown("P")) a.Play();
if (Input.GetKeyDown("R")) a.Rewind();
// playing: true while it plays. time: seconds into the clip (can be set to scrub).
if (a.playing && a.time > 2f) a.time = 0.5f;
}
}
CharacterController
class CharacterController
Walks and jumps the object like a player: a capsule that slides along walls, climbs low steps and falls under gravity (the CharacterController component).
| Member | Description | Example |
|---|---|---|
float speed | Walk speed, units per second. | c.speed = Input.GetKey("Shift") ? run : walk; |
float jumpSpeed | Upward speed of a jump, units per second. | c.jumpSpeed = 6f; |
bool isGrounded | Standing on something. | if (c.isGrounded && Input.GetActionDown("Jump")) c.Jump(); |
float verticalSpeed | Vertical speed now (positive = rising). | if (!c.isGrounded && c.verticalSpeed < -12f) Camera.Shake(0.2f, 0.3f); |
void Move(float x, float z) | Walks in the direction (x, z) until changed: length 1 is full speed, (0, 0) stands still. | c.Move((Input.mouseWorldPosition - transform.position).Normalized); |
void Move(Vector3 direction) | Walks in the direction of the vector's x and z. | c.Move((Input.mouseWorldPosition - transform.position).Normalized); |
void Jump() | Jumps if standing on something. | if (c.isGrounded && Input.GetActionDown("Jump")) c.Jump(); |
Example (CharacterController.cs)
// CharacterController: walks and jumps an object like a player: slides along walls, climbs steps, falls.
public class CharacterControllerExample : Behaviour
{
public float walk = 4f;
public float run = 7f;
public override void Update(float deltaTime)
{
CharacterController c = gameObject.character;
// speed: walk speed in units a second. jumpSpeed: the upward speed of a jump.
c.speed = Input.GetKey("Shift") ? run : walk;
c.jumpSpeed = 6f;
// Move(x, z): walk in a direction until told otherwise: length 1 is full speed, (0, 0) stands still.
float x = Input.GetAxis("Horizontal");
float z = -Input.GetAxis("Vertical");
if (Input.GetMouseButton(1))
// Move(Vector3): the same from a vector's x and z: here, towards where the pointer is on the ground.
c.Move((Input.mouseWorldPosition - transform.position).Normalized);
else
c.Move(x, z);
// isGrounded: standing on something. Jump: jumps when grounded.
if (c.isGrounded && Input.GetActionDown("Jump")) c.Jump();
// verticalSpeed: how fast it rises (positive) or falls (negative): a hard landing shakes the camera.
if (!c.isGrounded && c.verticalSpeed < -12f) Camera.Shake(0.2f, 0.3f);
}
}
NavAgent
class NavAgent
Walks the object across the baked navigation area to a destination, around obstacles (the NavAgent component).
| Member | Description | Example |
|---|---|---|
Vector3 destination | Where the agent is walking to. | if (agent.hasPath) Debug.Log("heading for " + agent.destination + ", " + agent.remainingDistance + " m to g... |
float speed | Walking speed, units per second. | agent.speed = 5f; |
float stoppingDistance | The agent stops this far from its destination. | agent.stoppingDistance = 1.5f; |
float remainingDistance | Distance left along the path (0 when idle or arrived). | if (agent.hasPath) Debug.Log("heading for " + agent.destination + ", " + agent.remainingDistance + " m to g... |
bool hasPath | The agent is on its way (false when idle, arrived or there is no path). | if (agent.hasPath) Debug.Log("heading for " + agent.destination + ", " + agent.remainingDistance + " m to g... |
bool arrived | The agent has a destination and is not walking any more. | if (agent.arrived && far < 2f) player.SendMessage("TakeDamage", 10f * deltaTime); |
void SetDestination(Vector3 target) | Walks to target (paths are planned on the next frame). | agent.SetDestination(player.transform.position); |
void Stop() | Stands still where it is. | if (Input.GetKeyDown("F")) agent.Stop(); |
void Patrol(Vector3[] points, float pause = 1f) | Walks a loop of waypoints, around obstacles, resting pause seconds at each. Call it every frame from Update with the same points (the agent turns to face where it walks by itself). | agent.Patrol(route, 2f); |
Example (NavAgent.cs)
// NavAgent: walks an object across the walkable area to a place, around obstacles (the NavAgent component).
public class NavAgentExample : Behaviour
{
public Vector3[] route = { new Vector3(0, 0, 0), new Vector3(8, 0, 0), new Vector3(8, 0, -8) };
public float sight = 10f;
public override void Update(float deltaTime)
{
NavAgent agent = gameObject.agent;
GameObject player = GameObject.FindPlayer();
float far = Vector3.Distance(transform.position, player.transform.position);
if (far < sight)
{
// speed: walking speed. stoppingDistance: how far from the destination it stops.
agent.speed = 5f;
agent.stoppingDistance = 1.5f;
// SetDestination: walk there (the path is planned on the next frame).
agent.SetDestination(player.transform.position);
}
else
{
agent.speed = 2f;
// Patrol: walk a loop of points, resting at each (call it every frame while patrolling).
agent.Patrol(route, 2f);
}
// destination: where it is walking to. remainingDistance: how much of the path is left.
// hasPath: it is on its way. arrived: it has a destination and has stopped walking.
if (agent.hasPath) Debug.Log("heading for " + agent.destination + ", " + agent.remainingDistance + " m to go");
if (agent.arrived && far < 2f) player.SendMessage("TakeDamage", 10f * deltaTime);
// Stop: stand still where it is.
if (Input.GetKeyDown("F")) agent.Stop();
}
}
Component
class Component
A built-in component of an object as a script holds it: GetComponent<AudioSource>(), GetComponent<Light>(), or any one by its Inspector name, GetComponent("ParticleSystem"), whose fields Set changes while playing.
| Member | Description | Example |
|---|---|---|
GameObject gameObject | The object it is on. | Component smoke = gameObject.GetComponent("ParticleSystem"); |
Transform transform | The transform of the object it is on. | Debug.Log(smoke.type + " on " + smoke.gameObject.name + " at " + smoke.transform.position); |
string type | Its name as the Inspector shows it, such as "PointLight". | Debug.Log(smoke.type + " on " + smoke.gameObject.name + " at " + smoke.transform.position); |
bool enabled | Switched on; false takes it out of the game until it is switched back on, as it was. | smoke.enabled = false; |
void Set(string field, float value) | Changes one of its number fields while playing: c.Set("intensity", 3f). | smoke.Set("rate", 40f); |
void Set(string field, bool value) | Changes one of its true/false fields. | smoke.Set("rate", 40f); |
void Set(string field, string value) | Changes one of its text fields. | smoke.Set("rate", 40f); |
void Set(string field, Vector3 value) | Changes one of its colour or vector fields. | smoke.Set("rate", 40f); |
Example (Component.cs)
// Component: a built-in component of an object, reached by its Inspector name when it has no C# type of its own.
public class ComponentExample : Behaviour
{
public override void Start()
{
// GetComponent("Name"): the component, or null when the object has none.
Component smoke = gameObject.GetComponent("ParticleSystem");
if (smoke == null) return;
// gameObject, transform, type: what it is on, and its Inspector name.
Debug.Log(smoke.type + " on " + smoke.gameObject.name + " at " + smoke.transform.position);
// Set: change one of its fields while playing: a number, true/false, text, or a vector / colour.
smoke.Set("rate", 40f);
smoke.Set("looping", true);
smoke.Set("effect", "");
smoke.Set("color", new Vector3(0.6f, 0.6f, 0.6f));
// enabled: false takes it out of the game until it is switched back on, as it was.
smoke.enabled = false;
smoke.enabled = true;
}
}
AudioSource
class AudioSource : Component
The object's AudioSource: GetComponent<AudioSource>().Play().
| Member | Description | Example |
|---|---|---|
void Play() | Plays its clip from the start (whether or not it plays on awake). | source.Play(); |
void Stop() | Stops it until it is played again. | if (Input.GetKeyDown("M")) source.Stop(); |
void PlayOneShot(AudioClip clip, float volumeScale = 1f) | Plays another sound once from the object, over what it is playing. | if (Input.GetKeyDown("Space")) source.PlayOneShot(ding); |
string clip | Its sound file, a project path such as "Audio/Door.wav" (changing it plays the new one). | source.clip = "Audio/Engine.wav"; |
float volume | How loud it is, 0..1. | source.volume = 0.8f; |
float pitch | Its speed: 1 normal, 2 an octave up. | source.pitch = 1.2f; |
bool loop | Whether it starts again when it ends. | source.loop = true; |
bool isPlaying | True while its sound is playing (not when it has ended or was stopped, or is waiting out its start delay). | |
bool mute | Silences it without stopping it. | |
float pan | Which ear it favours (-1 left, 1 right) when it is not spatial. | |
bool spatial | Whether it is quieter and panned by its distance from the listener. | |
float radius | Where a spatial source falls silent, in metres. | |
string bus | The mixer bus it plays on ("Music", "SFX" ...). |
Example (AudioSource.cs)
// AudioSource: the object's AudioSource component: play it, stop it, change how it sounds.
public class AudioSourceExample : Behaviour
{
public AudioClip ding;
AudioSource source;
public override void Start()
{
source = GetComponent<AudioSource>();
if (source == null) return;
// clip: the sound file it plays. volume (0..1), pitch (1 normal), loop: how it plays.
source.clip = "Audio/Engine.wav";
source.volume = 0.8f;
source.pitch = 1.2f;
source.loop = true;
// Play: from the start (whether or not it plays on awake).
source.Play();
}
public override void Update(float deltaTime)
{
if (source == null) return;
// PlayOneShot: another sound, once, over what it plays. Stop: quiet until played again.
if (Input.GetKeyDown("Space")) source.PlayOneShot(ding);
if (Input.GetKeyDown("M")) source.Stop();
}
}
Light
class Light : Component
The object's light (PointLight, SpotLight, DirectionalLight or Light2D): GetComponent<Light>().intensity = 2f.
| Member | Description | Example |
|---|---|---|
float intensity | How bright it is. | lamp.intensity = 2f + Mathf.Sin(t * 20f) * 0.3f; |
Color color | Its colour. | lamp.color = new Color(1f, 0.7f, 0.4f); |
float range | How far it reaches (point and spot lights). | lamp.range = 8f; |
Example (Light.cs)
// Light: the object's light (point, spot, directional or 2D).
public class LightExample : Behaviour
{
float t;
public override void Update(float deltaTime)
{
Light lamp = GetComponent<Light>();
if (lamp == null) return;
t += deltaTime;
// intensity, color, range: how bright, what colour, how far it reaches. A flicker:
lamp.intensity = 2f + Mathf.Sin(t * 20f) * 0.3f;
lamp.color = new Color(1f, 0.7f, 0.4f);
lamp.range = 8f;
}
}
MeshRenderer
class MeshRenderer : Component
What draws the object (its MeshRenderer, or a 2D object's SpriteRenderer): switch it off with enabled.
| Member | Description | Example |
|---|---|---|
string material | A project material such as "Materials/Gold.mat". | if (Input.GetKeyDown("G")) look.material = "Materials/Gold.mat"; |
Example (MeshRenderer.cs)
// MeshRenderer: what draws the object: switch it off to hide it, or give it another material.
public class MeshRendererExample : Behaviour
{
public override void Update(float deltaTime)
{
MeshRenderer look = GetComponent<MeshRenderer>();
if (look == null) return;
// enabled: hidden while false (the object is still there, and still collides).
if (Input.GetKeyDown("H")) look.enabled = !look.enabled;
// material: a project material.
if (Input.GetKeyDown("G")) look.material = "Materials/Gold.mat";
}
}
Collider
class Collider : Component { }
The object's collider (box, sphere, capsule, mesh, or a 2D one): GetComponent<Collider>().enabled = false.
Example (Collider.cs)
// Collider: the object's collider (box, sphere, capsule, mesh or 2D): switch it off and things pass through.
public class ColliderExample : Behaviour
{
public override void OnTriggerEnter(GameObject other)
{
// a door that opens when the player walks up: its collider goes, so the player walks through
Collider wall = GetComponent<Collider>();
if (wall != null && other.CompareTag("Player")) wall.enabled = false;
}
}
Events
static class Events
Messages between scripts that do not know each other's types: Events.Emit("DoorOpened", "Cellar Door") reaches everyone who called Events.On("DoorOpened", ...).
| Member | Description | Example |
|---|---|---|
static void On(string name, Action<object> handler) | Calls handler with the argument every time name is emitted. | Events.On("CoinPicked", onCoin); |
static void On(string name, Action handler) | Calls handler every time name is emitted. | Events.On("CoinPicked", onCoin); |
static void Off(string name, Action<object> handler) | Stops calling a handler added with On. | Events.Off("CoinPicked", onCoin); |
static void Off(string name, Action handler) | Stops calling a handler that takes no argument, added with On. | Events.Off("CoinPicked", onCoin); |
static void Emit(string name, object arg = null) | Tells everyone who listens to name. | Events.Emit("CoinPicked", 5); |
Example (Events.cs)
// Events: messages between scripts that do not know about each other.
public class EventsExample : Behaviour
{
int coins;
System.Action<object> onCoin;
public override void OnEnable()
{
// On with an argument: called with what was emitted, every time the name is emitted.
onCoin = amount => { coins += (int)amount; UI.SetText("Coins", coins.ToString()); };
Events.On("CoinPicked", onCoin);
// On without an argument.
Events.On("PlayerDied", () => UI.SetVisible("GameOver", true));
}
public override void OnDisable()
{
// Off: stop calling a handler added with On (keep the handler in a field to do this).
Events.Off("CoinPicked", onCoin);
}
}
// Somewhere else, a coin tells whoever listens. It does not know the HUD exists.
public class EventsExampleCoin : Behaviour
{
public override void OnTriggerEnter(GameObject other)
{
// Emit: tell everyone who listens to the name, with an optional value.
Events.Emit("CoinPicked", 5);
if (transform.position.y < -10f) Events.Emit("PlayerDied");
GameObject.Destroy(gameObject);
}
}
Inventory
static class Inventory
What the player carries: keys, coins, potions. Inventory.Add("Key"), Inventory.Has("Key"), Inventory.Take("Key"). Changes are announced with Events.Emit("InventoryChanged", item).
| Member | Description | Example |
|---|---|---|
static void Add(string item, int amount = 1) | Adds amount of an item. | if (other.CompareTag("Key")) Inventory.Add("Key"); |
static bool Has(string item, int amount = 1) | True when at least amount of the item are carried. | if (!Inventory.Has("Key")) { UI.SetText("Hint", "It is locked"); return; } |
static int Count(string item) | How many of the item are carried. | if (Inventory.Count("Coin") >= 25 && Inventory.Take("Coin", 25)) Inventory.Add("Potion"); |
static bool Take(string item, int amount = 1) | Uses up amount of an item; false (and nothing taken) when there is not enough. | Inventory.Take("Key"); |
static List<string> All() | The names of everything carried. | if (Input.GetKeyDown("I")) UI.SetText("Bag", string.Join(", ", Inventory.All())); |
static void Clear() | Empties the inventory. | if (Input.GetKeyDown("F1")) Inventory.Clear(); |
Example (Inventory.cs)
// Inventory: what the player carries: keys, coins, potions.
public class InventoryExample : Behaviour
{
public override void OnTriggerEnter(GameObject other)
{
// Add: add one of an item, or an amount.
if (other.CompareTag("Key")) Inventory.Add("Key");
if (other.CompareTag("Coins")) Inventory.Add("Coin", 10);
GameObject.Destroy(other);
}
public void TryOpenDoor(GameObject door)
{
// Has: at least one (or an amount) is carried. Take: use it up; false when there is not enough.
if (!Inventory.Has("Key")) { UI.SetText("Hint", "It is locked"); return; }
Inventory.Take("Key");
door.SetActive(false);
}
public void BuyPotion()
{
// Count: how many of an item are carried.
if (Inventory.Count("Coin") >= 25 && Inventory.Take("Coin", 25)) Inventory.Add("Potion");
else UI.SetText("Hint", "Not enough coins (" + Inventory.Count("Coin") + " of 25)");
}
public override void Update(float deltaTime)
{
// All: the names of everything carried.
if (Input.GetKeyDown("I")) UI.SetText("Bag", string.Join(", ", Inventory.All()));
// Has with an amount; Clear: empty the inventory (a new game).
if (Inventory.Has("Coin", 100)) UI.SetText("Hint", "Rich!");
if (Input.GetKeyDown("F1")) Inventory.Clear();
}
}
Tween
class Tween
Things that change over time without a Update method: Tween.Move(door, up, 1.5f).Then(() => ...). Eases are "inout" (default, smooth start and end), "linear", "in", "out".
| Member | Description | Example |
|---|---|---|
bool done | True once it has finished or been cancelled. | if (fade != null && !fade.done && Input.GetKeyDown("Space")) fade.Cancel(); |
static Tween Value(float from, float to, float seconds, Action<float> apply, string ease = "inout") | Changes a number from from to to; apply gets each value. | fade = Tween.Value(0f, 1f, 2f, v => UI.SetColor("FadePanel", 0f, 0f, 0f, v), "linear"); |
static Tween Move(GameObject go, Vector3 to, float seconds, string ease = "inout") | Slides an object to a world position. | Tween open = Tween.Move(door, door.transform.position + Vector3.up * 3f, 1.5f); |
static Tween Rotate(GameObject go, Vector3 toEuler, float seconds, string ease = "inout") | Turns an object to these Euler angles (degrees). | Tween.Rotate(chestLid, new Vector3(-110f, 0f, 0f), 0.8f, "out").After(1.5f); |
static Tween Scale(GameObject go, Vector3 to, float seconds, string ease = "inout") | Resizes an object to this scale. | Tween.Scale(other, Vector3.one * 1.3f, 0.15f).Then(() => Tween.Scale(other, Vector3.one, 0.15f)); |
Tween Then(Action action) | Runs action when the tween ends (at once when it already has). | open.Then(() => Audio.Play("Audio/door-open.wav")); |
Tween After(float seconds) | Starts only after this many seconds. | Tween.Rotate(chestLid, new Vector3(-110f, 0f, 0f), 0.8f, "out").After(1.5f); |
void Cancel() | Stops it where it is (Then actions do not run). | if (fade != null && !fade.done && Input.GetKeyDown("Space")) fade.Cancel(); |
static void CancelAll(GameObject go) | Stops every tween on an object. | if (Input.GetKeyDown("Escape")) Tween.CancelAll(door); |
Example (Tween.cs)
// Tween: things that change over time without an Update method: doors, pop-ups, fades.
public class TweenExample : Behaviour
{
public GameObject door;
public GameObject chestLid;
Tween fade;
public override void OnTriggerEnter(GameObject other)
{
// Move: slide an object to a world position over some seconds. Eases: "inout" (the default), "linear", "in", "out"...
Tween open = Tween.Move(door, door.transform.position + Vector3.up * 3f, 1.5f);
// Then: run something when the tween ends.
open.Then(() => Audio.Play("Audio/door-open.wav"));
// Rotate: turn an object to these Euler angles. After: start only after a delay.
Tween.Rotate(chestLid, new Vector3(-110f, 0f, 0f), 0.8f, "out").After(1.5f);
// Scale: resize an object (a pickup that pops).
Tween.Scale(other, Vector3.one * 1.3f, 0.15f).Then(() => Tween.Scale(other, Vector3.one, 0.15f));
// Value: change any number; the action gets each value on the way (a screen fade).
fade = Tween.Value(0f, 1f, 2f, v => UI.SetColor("FadePanel", 0f, 0f, 0f, v), "linear");
}
public override void Update(float deltaTime)
{
// done: true once a tween finished or was cancelled. Cancel: stop it where it is (its Then actions do not run).
if (fade != null && !fade.done && Input.GetKeyDown("Space")) fade.Cancel();
// CancelAll: stop every tween on an object.
if (Input.GetKeyDown("Escape")) Tween.CancelAll(door);
}
}
ModelAnimation
class ModelAnimation
What a script can ask of an object's skinned model animation (the ModelAnimator component; the object needs one). A character that walks (CharacterController, NavAgent or moved by a script) with locomotion on plays its idle, walk and run clips by itself from how fast it really moves: a script only adds the one-off clips on top.
| Member | Description | Example |
|---|---|---|
void Play(string clip) | Plays a clip of the model once from its start, over everything else, and then goes back to what the object was doing (an attack, a hit, a wave). Asking again restarts it. The name is one of the model's clips (see model_info); an unknown name is ignored. | if (Input.GetAction("Fire")) m.Play("Attack"); |
void Play(string clip, string bone) | Plays a clip once on part of the body only, from bone down ("Spine": the upper body), while the rest keeps doing what it was doing: an attack or a wave while the legs keep running. The bone is one of the model's (a rig's prefix such as mixamorig: may be left out); "" plays it on the whole body. | if (Input.GetAction("Fire")) m.Play("Attack"); |
void SetBlendShape(string name, float weight) | Sets one of the model's blend shapes (morph targets: a smile, a blink, a surprised face) by name, usually from 0 to 1. It stays until set again and wins over what an animation gives it. The names are the model's (see model_info). | m.SetBlendShape("Blink", blink > 0.9f ? 1f : 0f); |
void SetLayerWeight(int layer, float weight) | How much one of the object's animation layers (its AnimationLayers component, layer 1 the first listed) shows, from 0 (off) to 1: fade an aiming pose in while holding a weapon, out when putting it away. | m.SetLayerWeight(1, Input.GetMouseButton(1) ? 1f : 0f); |
void Loop(string clip) | Switches the object to one clip that loops, and turns walking animation (locomotion) off. Use it for things that do not walk: a spinning fan, a character that dances. | if (Input.GetKeyDown("G")) m.Loop("Dance"); |
bool locomotion | Turns the automatic idle / walk / run clips on or off (reads back what a script last set; on at first). | if (Input.GetKeyDown("H")) m.locomotion = true; |
float speed | How fast animations run (1 = normal; reads back what a script last set). | m.speed = Input.GetKey("Shift") ? 1.5f : 1f; |
bool paused | Freezes the model's animation (or lets it run again; reads back what a script last set). | if (Input.GetKeyDown("P")) m.paused = !m.paused; |
Example (ModelAnimation.cs)
// ModelAnimation: a skinned model's animations (the ModelAnimator component): one-off clips, loops, faces, layers.
public class ModelAnimationExample : Behaviour
{
float blink;
public override void Update(float deltaTime)
{
ModelAnimation m = gameObject.model;
// Play: plays a clip of the model once over everything else, then goes back to walking or standing.
if (Input.GetAction("Fire")) m.Play("Attack");
// Play on part of the body: from a bone down ("Spine": the upper body), so the legs keep walking.
if (Input.GetKeyDown("R")) m.Play("Reload", "Spine");
// SetBlendShape: one of the model's blend shapes (a blink, a smile) by name, 0 to 1.
blink = Mathf.PingPong(Time.time * 4f, 1f);
m.SetBlendShape("Blink", blink > 0.9f ? 1f : 0f);
// SetLayerWeight: how much one of the object's animation layers shows (layer 1 is the first listed).
m.SetLayerWeight(1, Input.GetMouseButton(1) ? 1f : 0f); // an aiming pose on the arms
// speed: how fast animations run. paused: freeze or release the model.
m.speed = Input.GetKey("Shift") ? 1.5f : 1f;
if (Input.GetKeyDown("P")) m.paused = !m.paused;
// locomotion: the automatic idle / walk / run clips. Loop: one clip that loops instead (it turns locomotion off).
if (Input.GetKeyDown("G")) m.Loop("Dance");
if (Input.GetKeyDown("H")) m.locomotion = true;
}
}
Subtitles
static class Subtitles
Captions drawn over the game: Subtitles.Show("Open the gate!", 3f, "Guard"). An AudioSource with a Subtitle shows it by itself while its sound plays. A player (or your options screen) can switch them off with Subtitles.enabled = false; Achievements and other short notices use Subtitles.Toast.
| Member | Description |
|---|---|
static bool enabled | Whether captions show (on at first). It is remembered between runs. |
static void Show(string text, float seconds = 3f, string speaker = null) | A caption at the bottom of the screen for some seconds, with who says it in front when given. |
static void Toast(string text, float seconds = 4f) | A short notice at the top of the screen (shown whether or not captions are on). |
Achievements
static class Achievements
Achievements kept with the game's saved values (PlayerPrefs): Achievements.Unlock("first_coin", "First coin") shows a notice the first time and returns true; later it does nothing and returns false. They are local to this computer: a store's own achievements (Steam and others) are not connected.
| Member | Description |
|---|---|
static bool IsUnlocked(string id) | Whether it was unlocked (now or in an earlier run). |
static bool Unlock(string id, string title = null) | Unlocks it: a notice "Achievement unlocked: title" for a few seconds, once. Returns whether it was new. |
static List<string> Unlocked() | The ids unlocked so far. |
static void Reset() | Locks them all again (a "new game" for testing). |
BtStatus
enum BtStatus
What a behaviour tree node says when it is ticked.
| Member | Description |
|---|---|
Running | Still going: it is ticked again next frame. |
Success | Done, and it worked. |
Failure | Done, and it did not work. |
BtNode
class BtNode
A node of a behaviour tree (see BT): tick the root every frame.
| Member | Description |
|---|---|
abstract BtStatus Tick() | Runs the node for this frame. |
virtual void Reset() | Forgets what it was in the middle of (a sequence starts from its first child again). |
BT
static class BT
Behaviour trees for characters and enemies, without a component: build the tree once and tick it every frame. var tree = BT.Selector( BT.Sequence(BT.Condition(() => CanSeePlayer()), BT.Action(() => Chase())), BT.Action(() => Patrol())); // in Update: tree.Tick(); A Sequence runs its children in order and stops at the first that fails; a Selector tries them in order until one succeeds. A child that answers Running is ticked again next frame (its siblings before it are not run again).
| Member | Description |
|---|---|
static BtNode Sequence(params BtNode[] children) | Children in order: Success when all succeed, Failure at the first that fails. |
static BtNode Selector(params BtNode[] children) | Children in order: Success at the first that succeeds, Failure when all fail. |
static BtNode Action(Func<BtStatus> f) | Something to do: return Success, Failure or Running. |
static BtNode Do(Action f) | Something to do that is done in one tick (always Success). |
static BtNode Condition(Func<bool> test) | Success when the test is true, Failure when it is not. |
static BtNode Inverter(BtNode n) | Swaps Success and Failure. |
static BtNode Succeeder(BtNode n) | Always Success, whatever the child did (when it is done). |
static BtNode Repeat(BtNode n, int times) | Runs the child that many times (Failure if it fails once). |
static BtNode Wait(float seconds) | Running for this many seconds of game time, then Success. |
static BtNode Cooldown(BtNode n, float seconds) | Runs the child at most once in this many seconds; in between it fails (a gun that cannot fire again yet). |