Cette page n'est pas encore traduite : elle s'affiche en anglais.

Script cookbook

22 complete scripts for the jobs most games have: moving a character, picking things up, doors, enemies, health, saving, menus. Each compiles as it stands: save it in your project's Scripts/ folder under the name shown, add it to an object with Add Component, and change it to suit. Every type they use is in the API reference, with an example for each member.

Walk and jump

A character moved with the arrow keys or a stick, that jumps with Space. Put it on an object that has a CharacterController (GameObject > 3D Object > Capsule, then Add Component).

Scripts/PlayerWalk.cs

public class PlayerWalk : Behaviour
{
    public float walkSpeed = 5f;
    public float jumpSpeed = 7f;

    public override void Start()
    {
        gameObject.character.speed = walkSpeed;
        gameObject.character.jumpSpeed = jumpSpeed;
    }

    public override void Update(float deltaTime)
    {
        // "Horizontal" and "Vertical" are -1..1 from the arrows, WASD or a gamepad's left stick.
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        gameObject.character.Move(x, z);

        // Jump is an input action (Space, or the south button of a gamepad): only from the ground.
        if (Input.GetActionDown("Jump") && gameObject.character.isGrounded)
            gameObject.character.Jump();
    }
}

A coin to collect

It spins, and when the player walks into it the score goes up and the coin is gone. Put it on an object with a Trigger3D; the player needs the tag "Player". A UI text named "Score" shows the count.

Scripts/Coin.cs

public class Coin : Behaviour
{
    public int worth = 1;
    public float turnsPerSecond = 0.5f;

    public override void Update(float deltaTime)
    {
        transform.Rotate(new Vector3(0f, 360f * turnsPerSecond * deltaTime, 0f));
    }

    public override void OnTriggerEnter(GameObject other)
    {
        if (!other.CompareTag("Player")) return;
        Inventory.Add("coin", worth);
        UI.SetText("Score", "Coins " + Inventory.Count("coin"));
        Audio.PlayAt("Audio/coin.wav", transform.position);
        GameObject.Destroy(gameObject);
    }
}

A sliding door

It opens when the player comes near and closes behind them. Put it on the door; give the door (or a box in front of it) a Trigger3D that reaches where the player stands.

Scripts/SlidingDoor.cs

public class SlidingDoor : Behaviour
{
    public Vector3 slide = new Vector3(0f, 2.4f, 0f);
    public float seconds = 0.6f;

    Vector3 closed;

    public override void Start() { closed = transform.position; }

    public override void OnTriggerEnter(GameObject other)
    {
        if (!other.CompareTag("Player")) return;
        Tween.CancelAll(gameObject);
        Tween.Move(gameObject, closed + slide, seconds, "out");
    }

    public override void OnTriggerExit(GameObject other)
    {
        if (!other.CompareTag("Player")) return;
        Tween.CancelAll(gameObject);
        // wait a moment before closing, so it does not shut on someone's heels
        Tween.Move(gameObject, closed, seconds, "in").After(0.8f);
    }
}

A guard

It walks between points and runs at the player when it can see them. Put it on an object with a NavAgent. Name some empty objects "Post 1", "Post 2"... for its round.

Scripts/Guard.cs

public class Guard : Behaviour
{
    public float sight = 12f;
    public float chaseSpeed = 5f;
    public float walkSpeed = 2f;

    GameObject player;
    bool chasing;

    public override void Start()
    {
        player = GameObject.FindPlayer();
        Round();
    }

    void Round()
    {
        var posts = new System.Collections.Generic.List<Vector3>();
        for (int n = 1; GameObject.Find("Post " + n) != null; n++) posts.Add(GameObject.Find("Post " + n).transform.position);
        gameObject.agent.speed = walkSpeed;
        if (posts.Count > 0) gameObject.agent.Patrol(posts.ToArray(), 1.5f);
        chasing = false;
    }

    public override void Update(float deltaTime)
    {
        if (player == null) return;
        Vector3 eyes = transform.position + Vector3.up * 1.6f;
        Vector3 them = player.transform.position + Vector3.up * 1f;
        // seen: near enough, and nothing but the player on the line between the two
        bool near = Vector3.Distance(eyes, them) < sight;
        bool seen = near && (!Physics.Linecast(eyes, them, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject) || hit.gameObject == player);
        if (seen)
        {
            chasing = true;
            gameObject.agent.speed = chaseSpeed;
            gameObject.agent.SetDestination(player.transform.position);
        }
        else if (chasing && gameObject.agent.arrived)
        {
            // lost them: back to the round
            Round();
        }
    }
}

Health with a bar

The object loses health when something calls TakeDamage on it, and is destroyed at zero. A UI slider named "Health Bar" shows the player's health. Other scripts hit it with:

target.SendMessage("TakeDamage", 25f);

Scripts/Health.cs

public class Health : Behaviour
{
    public float max = 100f;
    public bool showsOnBar = true;

    float now;

    public override void Start()
    {
        now = max;
        Show();
    }

    // (SendMessage finds this by its name)
    public void TakeDamage(object amount)
    {
        now = Mathf.Max(0f, now - System.Convert.ToSingle(amount));
        Show();
        if (now <= 0f)
        {
            // whoever keeps the score or ends the level hears of it
            Events.Emit("died", gameObject.name);
            GameObject.Destroy(gameObject);
            return;
        }
        // a red flash that fades back
        Tween.Value(0f, 1f, 0.2f, t => gameObject.SetColor(Color.Lerp(Color.red, Color.white, t)));
    }

    void Show()
    {
        if (showsOnBar && UI.Exists("Health Bar")) UI.SetValue("Health Bar", now / max);
    }
}

A turret

It turns to the player and shoots a ball at them every so often, when nothing is in the way. Put it on the turret's head. The balls are spheres with a rigid body, gone after a few seconds.

Scripts/Turret.cs

using System.Collections;

public class Turret : Behaviour
{
    public float range = 20f;
    public float secondsBetweenShots = 1.2f;
    public float shotSpeed = 18f;

    GameObject player;
    float wait;

    public override void Start() { player = GameObject.FindPlayer(); }

    public override void Update(float deltaTime)
    {
        if (player == null) return;
        Vector3 aim = player.transform.position + Vector3.up;
        if (Vector3.Distance(transform.position, aim) > range) return;
        transform.LookAt(aim);
        wait -= deltaTime;
        // a wall between the two stops the shot (the player themselves does not)
        bool blocked = Physics.Linecast(transform.position, aim, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject) && hit.gameObject != player;
        if (wait <= 0f && !blocked)
        {
            wait = secondsBetweenShots;
            StartCoroutine(Shoot());
        }
    }

    IEnumerator Shoot()
    {
        GameObject ball = GameObject.Spawn("Sphere", transform.position + transform.forward, Vector3.zero, new Vector3(0.3f, 0.3f, 0.3f));
        ball.SetColor(Color.red);
        ball.AddRigidbody(0.5f);
        ball.rigidbody.velocity = transform.forward * shotSpeed;
        Audio.PlayAt("Audio/shot.wav", transform.position);
        yield return new WaitForSeconds(4f);
        if (ball.exists) GameObject.Destroy(ball);
    }
}

Waves

A few more crates fall from above each wave, a little faster each time, until the last wave. Put it on an empty object where the crates should fall. A UI text named "Wave" says which wave it is.

Scripts/Spawner.cs

using System.Collections;

public class Spawner : Behaviour
{
    public int waves = 5;
    public int firstWave = 3;
    public float secondsBetweenWaves = 6f;
    public float spread = 6f;

    public override void Start() { StartCoroutine(Run()); }

    IEnumerator Run()
    {
        for (int wave = 1; wave <= waves; wave++)
        {
            if (UI.Exists("Wave")) UI.SetText("Wave", "Wave " + wave + " of " + waves);
            for (int n = 0; n < firstWave + wave - 1; n++)
            {
                Vector3 at = transform.position + new Vector3(Random.Range(-spread, spread), 8f + n, Random.Range(-spread, spread));
                GameObject crate = GameObject.Spawn("Cube", at);
                crate.AddRigidbody(2f);
                crate.SetColor(new Color(0.8f, 0.5f, 0.2f));
                // a short pause between crates, shorter each wave
                yield return new WaitForSeconds(Mathf.Max(0.1f, 0.5f - wave * 0.07f));
            }
            yield return new WaitForSeconds(secondsBetweenWaves);
        }
        Events.Emit("waves done");
    }
}

A pause menu

Escape stops the game and shows a panel; its buttons carry on, start the level again, or leave. Make a UI panel named "Pause Panel" with three buttons whose actions are "resume", "restart" and "quit".

Scripts/PauseMenu.cs

public class PauseMenu : Behaviour
{
    bool paused;

    public override void Start() { Set(false); }

    public override void Update(float deltaTime)
    {
        if (Input.GetKeyDown("Escape")) Set(!paused);
        if (!paused) return;
        // (a button reports the frame it was clicked, by the name of its action)
        if (UI.Clicked("resume")) Set(false);
        if (UI.Clicked("restart")) { Set(false); Scene.Reload(); }
        if (UI.Clicked("quit")) Application.Quit();
    }

    void Set(bool on)
    {
        paused = on;
        // time stands still while the panel is up: physics, animations and Update's deltaTime all stop
        Time.timeScale = on ? 0f : 1f;
        UI.SetVisible("Pause Panel", on);
        Cursor.visible = on;
    }
}

Save and load

F5 writes where everything is and what the player holds to a slot; F9 puts it all back. Put it on any object in the scene (a "Game" object is the usual place).

Scripts/SaveSlots.cs

public class SaveSlots : Behaviour
{
    public string slot = "1";

    public override void Update(float deltaTime)
    {
        if (Input.GetKeyDown("F5")) Save();
        if (Input.GetKeyDown("F9")) Load();
    }

    void Save()
    {
        // your own values go in a SaveData; SaveObjects adds where every object is, and which are gone
        var data = new SaveData();
        data.SetInt("coins", Inventory.Count("coin"));
        data.SetFloat("played", Time.time);
        data.SetString("scene", "Level 1");
        SaveGame.SaveObjects(slot, data);
        Debug.Log("saved to slot " + slot);
    }

    void Load()
    {
        if (!SaveGame.Exists(slot)) { Debug.LogWarning("slot " + slot + " is empty"); return; }
        // the objects go back to where they were, and your values come back
        SaveData data = SaveGame.LoadObjects(slot);
        Inventory.Clear();
        Inventory.Add("coin", data.GetInt("coins"));
        if (UI.Exists("Score")) UI.SetText("Score", "Coins " + Inventory.Count("coin"));
        Debug.Log("loaded slot " + slot + ", saved " + SaveGame.SavedAt(slot));
    }
}

A best score

Other scripts say what happened with events, this one counts and remembers the best. Anywhere in the game: Events.Emit("scored", 10); A UI text named "Score" shows both numbers.

Scripts/HighScore.cs

public class HighScore : Behaviour
{
    int score;
    int best;

    public override void Start()
    {
        best = PlayerPrefs.GetInt("best score");
        Events.On("scored", OnScored);
        Events.On("died", OnDied);
        Show();
    }

    void OnScored(object points)
    {
        score += System.Convert.ToInt32(points);
        Show();
    }

    void OnDied(object who)
    {
        if (score > best)
        {
            best = score;
            PlayerPrefs.SetInt("best score", best);
            PlayerPrefs.Save();
        }
        Show();
    }

    public override void OnDestroy()
    {
        // (a script that listens stops listening when it goes: the handler would be called on a dead object)
        Events.Off("scored", OnScored);
        Events.Off("died", OnDied);
    }

    void Show()
    {
        if (UI.Exists("Score")) UI.SetText("Score", "Score " + score + "   Best " + best);
    }
}

Click to move

The character walks to where the pointer was clicked on the ground, round what is in the way. Put it on an object with a NavAgent. A small sphere named "Marker" (optional) shows where it is going.

Scripts/ClickToMove.cs

public class ClickToMove : Behaviour
{
    GameObject marker;

    public override void Start() { marker = GameObject.Find("Marker"); }

    public override void Update(float deltaTime)
    {
        if (Input.GetMouseButtonDown(0))
        {
            // a ray from the camera through the pointer: where it meets something is where to go
            Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit, 500f))
            {
                gameObject.agent.SetDestination(hit.point);
                if (marker != null) marker.transform.position = hit.point + Vector3.up * 0.1f;
            }
        }
        if (marker != null) marker.SetActive(!gameObject.agent.arrived);
    }
}

An exploding barrel

It blows up when it is shot or hit hard, and everything near is pushed away and hurt, and the camera shakes. Put it on the barrel (with a rigid body). Bullets call: barrel.SendMessage("TakeDamage", 50f);

Scripts/Explosive.cs

public class Explosive : Behaviour
{
    public float radius = 6f;
    public float push = 12f;
    public float damage = 60f;

    bool gone;

    public void TakeDamage(object amount) { Explode(); }

    public override void OnCollisionEnter(GameObject other)
    {
        // something fast ran into it
        if (other.rigidbody.exists && other.rigidbody.velocity.Length > 8f) Explode();
    }

    void Explode()
    {
        if (gone) return;
        gone = true;
        foreach (GameObject near in Physics.OverlapSphere(transform.position, radius, gameObject))
        {
            // nearer things are pushed harder and hurt more
            Vector3 away = near.transform.position - transform.position;
            float strength = 1f - Mathf.Clamp01(away.Length / radius);
            if (near.rigidbody.exists) near.rigidbody.AddImpulse((away.Normalized + Vector3.up * 0.5f) * push * strength);
            near.SendMessage("TakeDamage", damage * strength);
        }
        Camera.Shake(0.6f, 0.5f);
        Audio.PlayAt("Audio/explosion.wav", transform.position, 1f, 1f, 60f);
        GameObject.Destroy(gameObject);
    }
}

A moving platform

It glides between where it starts and a second point, waits a moment at each end, and carries what stands on it. Put it on the platform (a flat cube with a collider).

Scripts/MovingPlatform.cs

public class MovingPlatform : Behaviour
{
    public Vector3 travel = new Vector3(6f, 0f, 0f);
    public float secondsEachWay = 3f;
    public float waitAtEnds = 1f;

    Vector3 home;
    Vector3 last;

    public override void Start()
    {
        home = transform.position;
        last = home;
        Go(true);
    }

    void Go(bool out_)
    {
        // one tween each way; when it ends, the next starts after the wait
        Tween.Move(gameObject, out_ ? home + travel : home, secondsEachWay, "inout").After(waitAtEnds).Then(() => Go(!out_));
    }

    public override void LateUpdate()
    {
        last = transform.position;
    }

    public override void OnCollisionStay(GameObject other)
    {
        // whatever rests on the platform moves by what the platform moved this frame
        Vector3 moved = transform.position - last;
        if (other.transform.position.y > transform.position.y) other.transform.Translate(moved);
    }
}

Checkpoints

The player goes back to the last checkpoint they touched when they fall off the world or die. Put it on the player. Checkpoints are objects with a Trigger3D and the tag "Checkpoint".

Scripts/Respawn.cs

public class Respawn : Behaviour
{
    public float fallLimit = -20f;

    Vector3 safe;

    public override void Start()
    {
        safe = transform.position;
        // anything can send the player back:   Events.Emit("respawn");
        Events.On("respawn", Back);
    }

    public override void OnTriggerEnter(GameObject other)
    {
        if (!other.CompareTag("Checkpoint")) return;
        safe = other.transform.position + Vector3.up;
        other.SetColor(Color.green);
    }

    public override void Update(float deltaTime)
    {
        if (transform.position.y < fallLimit) Back();
    }

    void Back()
    {
        transform.position = safe;
        if (gameObject.rigidbody.exists) gameObject.rigidbody.velocity = Vector3.zero;
        Camera.Shake(0.2f, 0.3f);
    }

    public override void OnDestroy() { Events.Off("respawn", Back); }
}

A countdown

The level has so many seconds; a text shows them, turns red near the end, and the level starts again at zero. Put it on any object. It needs a UI text named "Clock".

Scripts/Countdown.cs

using System.Collections;

public class Countdown : Behaviour
{
    public float seconds = 90f;
    public float warnBelow = 10f;

    float left;
    bool over;

    public override void Start()
    {
        left = seconds;
        // (reaching the exit stops the clock:   Events.Emit("level done");)
        Events.On("level done", Stop);
    }

    void Stop() { over = true; }

    public override void Update(float deltaTime)
    {
        if (over) return;
        left = Mathf.Max(0f, left - deltaTime);
        int whole = Mathf.CeilToInt(left);
        UI.SetText("Clock", (whole / 60) + ":" + (whole % 60).ToString("00"));
        UI.SetColor("Clock", left < warnBelow ? Color.red : Color.white);
        if (left <= 0f)
        {
            over = true;
            StartCoroutine(Again());
        }
    }

    IEnumerator Again()
    {
        UI.SetText("Clock", "Time is up");
        Events.Emit("time up");
        // (real seconds: the wait still ends if something has stopped the game's time)
        yield return new WaitForSecondsRealtime(2f);
        Scene.Reload();
    }

    public override void OnDestroy() { Events.Off("level done", Stop); }
}

Press E to use

A prompt appears when the player stands near something that can be used, and E uses the nearest one. Put it on the player. Things that can be used have the tag "Usable" and a script with a method OnInteract. It needs a UI text named "Prompt".

Scripts/Interact.cs

public class Interact : Behaviour
{
    public float reach = 2.5f;

    public override void Update(float deltaTime)
    {
        // the nearest usable thing within reach
        GameObject nearest = null;
        float best = reach;
        foreach (GameObject near in Physics.OverlapSphere(transform.position, reach, gameObject))
        {
            if (!near.CompareTag("Usable")) continue;
            float d = Vector3.Distance(transform.position, Physics.ClosestPoint(transform.position, near));
            if (d <= best) { best = d; nearest = near; }
        }
        UI.SetVisible("Prompt", nearest != null);
        if (nearest == null) return;
        UI.SetText("Prompt", "E  " + nearest.name);
        if (Input.GetKeyDown("E")) nearest.SendMessage("OnInteract", gameObject);
    }
}

A key to pick up

Walking into it puts it in what the player carries, for a lock to ask for later. Put it on the key, with a Trigger3D; the player needs the tag "Player".

Scripts/Key.cs

public class Key : Behaviour
{
    public string item = "brass key";

    public override void OnTriggerEnter(GameObject other)
    {
        if (!other.CompareTag("Player")) return;
        Inventory.Add(item);
        Audio.Play("Audio/pickup.wav");
        GameObject.Destroy(gameObject);
    }
}

A locked chest

It opens only for someone who holds its key, and shakes its head at anyone else. Put it on the chest's lid and give the lid the tag "Usable": the Interact script then calls OnInteract when E is pressed beside it.

Scripts/LockedChest.cs

public class LockedChest : Behaviour
{
    public string needs = "brass key";
    public Vector3 openAngle = new Vector3(-70f, 0f, 0f);

    bool open;

    // (the Interact script calls this by its name)
    public void OnInteract(object who)
    {
        if (open) return;
        if (!Inventory.Take(needs))
        {
            // locked: a small shake says no
            Vector3 rest = transform.position;
            Tween.Move(gameObject, rest + new Vector3(0.05f, 0f, 0f), 0.05f).Then(() => Tween.Move(gameObject, rest, 0.05f));
            return;
        }
        open = true;
        Tween.Rotate(gameObject, transform.rotation + openAngle, 0.8f, "out");
        Events.Emit("scored", 50);
    }
}

A bullet

It flies straight, hurts the first thing in its way and is gone; fast bullets do not pass through thin walls. Put it on a small sphere and save the sphere as a prefab (drag it into the Project panel). A gun then makes one with:

GameObject shot = GameObject.Instantiate("Prefabs/Bullet.prefab", muzzle);
shot.transform.rotation = transform.rotation;

Scripts/Bullet.cs

public class Bullet : Behaviour
{
    public float speed = 60f;
    public float damage = 25f;
    public float lifeSeconds = 3f;

    float age;

    public override void Update(float deltaTime)
    {
        Vector3 from = transform.position;
        Vector3 to = from + transform.forward * speed * deltaTime;
        // the whole step of this frame is checked, not only where the bullet ends up: at 60 m/s a frame's step is a metre
        if (Physics.Linecast(from, to, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject))
        {
            hit.gameObject.SendMessage("TakeDamage", damage);
            if (hit.gameObject.rigidbody.exists) hit.gameObject.rigidbody.AddImpulse(transform.forward * 2f);
            GameObject.Destroy(gameObject);
            return;
        }
        transform.position = to;
        age += deltaTime;
        if (age > lifeSeconds) GameObject.Destroy(gameObject);
    }
}

Animation from movement

The character's Animator is told how fast it moves, whether it stands on the ground and when it jumps. Put it on a character with a CharacterController and an Animator whose controller has a float "Speed", a bool "Grounded" and a trigger "Jump".

Scripts/WalkAnimation.cs

public class WalkAnimation : Behaviour
{
    Vector3 last;
    bool wasGrounded = true;

    public override void Start() { last = transform.position; }

    public override void Update(float deltaTime)
    {
        if (deltaTime <= 0f) return;
        // speed over the ground, from how far the character really moved (a wall stops it whatever the stick says)
        Vector3 moved = transform.position - last;
        moved.y = 0f;
        last = transform.position;
        gameObject.animator.SetFloat("Speed", moved.Length / deltaTime);

        bool grounded = gameObject.character.isGrounded;
        gameObject.animator.SetBool("Grounded", grounded);
        if (wasGrounded && !grounded && Input.GetAction("Jump")) gameObject.animator.SetTrigger("Jump");
        wasGrounded = grounded;

        // face the way it walks
        if (moved.Length > 0.01f) transform.LookAt(transform.position + moved);
    }
}

The way out

Stepping into it loads the next level in the background, with a bar that fills, and shows it when it is ready. Put it on an object with a Trigger3D. It needs a UI panel named "Loading" with a progress bar named "Loading Bar".

Scripts/LevelExit.cs

using System.Collections;

public class LevelExit : Behaviour
{
    public string nextScene = "Level 2";

    bool leaving;

    public override void Start() { UI.SetVisible("Loading", false); }

    public override void OnTriggerEnter(GameObject other)
    {
        if (leaving || !other.CompareTag("Player")) return;
        leaving = true;
        Events.Emit("level done");
        StartCoroutine(Leave());
    }

    IEnumerator Leave()
    {
        UI.SetVisible("Loading", true);
        SceneLoad load = Scene.LoadAsync(nextScene);
        // the scene is read while this one goes on; it is not shown until we say so
        load.allowSceneActivation = false;
        while (load.progress < 0.9f)
        {
            UI.SetValue("Loading Bar", load.progress);
            yield return null;
        }
        UI.SetValue("Loading Bar", 1f);
        yield return new WaitForSeconds(0.3f);
        load.allowSceneActivation = true;
    }
}

A controls menu

The player picks the key for Jump, the choice is kept for next time, and one button puts the default back. Put it on any object. It needs a UI text named "Jump Key" and two buttons whose actions are "change jump" and "default keys".

Scripts/ControlsMenu.cs

public class ControlsMenu : Behaviour
{
    bool waiting;

    public override void Start()
    {
        // the key chosen last time (PlayerPrefs keeps it between runs)
        string saved = PlayerPrefs.GetString("jump key");
        if (saved != "") Input.Rebind("Jump", saved);
        Show();
    }

    public override void Update(float deltaTime)
    {
        if (UI.Clicked("change jump"))
        {
            waiting = true;
            UI.SetText("Jump Key", "Press a key...");
            return;
        }
        if (UI.Clicked("default keys"))
        {
            Input.ResetBindings();
            PlayerPrefs.DeleteKey("jump key");
            waiting = false;
            Show();
        }
        if (!waiting) return;
        string key = Input.GetAnyKeyDown();
        if (key == null) return;
        // Escape gives up without changing anything
        if (key != "Escape")
        {
            Input.Rebind("Jump", key);
            PlayerPrefs.SetString("jump key", key);
            PlayerPrefs.Save();
        }
        waiting = false;
        Show();
    }

    void Show() { UI.SetText("Jump Key", "Jump: " + Input.GetBinding("Jump")); }
}