Tag Archives: script

Adding checkpoints to a 2D Unity game

This tutorial explains how to add checkpoints to a 2D game so that we can respawn the player back to a checkpoint when the player falls off a platform or off the map. This continues on from the previous tutorial on setting up the fall detector and will be completed when we add the ability to respawn in the next tutorial.

Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the CheckpointController script.

using UnityEngine;
using System.Collections;

public class CheckpointController : MonoBehaviour {

  public Sprite redFlag;
  public Sprite greenFlag;
  private SpriteRenderer checkpointSpriteRenderer;
  public bool checkpointReached;

  // Use this for initialization
  void Start () {
    checkpointSpriteRenderer = GetComponent<SpriteRenderer> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "Player") {
      checkpointSpriteRenderer.sprite = greenFlag;
      checkpointReached = true;
    }
  }
}

Next tutorial: Respawn the player

Making the camera follow the player in a 2D Unity game with code

This tutorial will show you how to write a script in C# code that will make the camera follow the player in a 2D Unity game. Watch the video below and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

  public GameObject player;
  public float offset;
  private Vector3 playerPosition;
  public float offsetSmoothing;

  // Use this for initialization
  void Start () {
  
  }
  
  // Update is called once per frame
  void Update () {
    playerPosition = new Vector3 (player.transform.position.x, transform.position.y, transform.position.z);
    if (player.transform.localScale.x > 0f) {
      playerPosition = new Vector3 (playerPosition.x + offset, playerPosition.y, playerPosition.z);
    }
    else {
      playerPosition = new Vector3(playerPosition.x - offset, playerPosition.y, playerPosition.z);
    }

    transform.position = Vector3.Lerp (transform.position, playerPosition, offsetSmoothing * Time.deltaTime);
  }
}

Next tutorial: Stopping the player from sticking to the edge of platforms and walls

Flipping the player with code in a 2D Unity game

This tutorial will show you how to flip your 2D game’s player sprite in Unity with C# code so that the player can turn and face the direction in which it is running, walking, or jumping.

Watch the video and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }
}

Next tutorial: Making the camera follow the player with code

Making the player jump in a 2D game with Unity and C# code

In this tutorial you will learn how to write a script to make your player jump in a 2D game with C# code in Unity. In the following tutorial, you will learn how to make the player jump only when they are touching the ground.

Watch the video below and scroll down to view the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
  }
  
  // Update is called once per frame
  void Update () {
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump")){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }
  }
}

Next tutorial:  Jumping with ground check

Introduction to C# scripting & collision detection for 2D games in Unity

This video gives an introduction to writing code for 2D games in Unity using the C# programming language. We’ll get started by adding collision detection so that our player object (or character) can collect points when colliding with coins in the game. You’ll learn how to setup 2D collision detection, increase a score variable, display messages in the console to test your code, and how to destroy objects (or make objects disappear) in a scene using code.

Watch the video below and scroll down to see the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class CoinScript : MonoBehaviour {

  public int score = 0;

  // Use this for initialization
  void Start () {
  
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    Destroy (gameObject);
    score++;
    Debug.Log ("Score: " + score);
  }
}

Next tutorial: Moving the player with C# code

Controlling audio with scripts

This tutorial explains how to control the audio in your game using scripts. You can play, stop, pause and resume sound effects and songs in your game when certain events occur by controlling the sound with code. This video explains how to do that and if you scroll down you will find the sample code.

The following sample code is used to control an audio source/slot called “song” that is attached to the same entity that the script is attached to. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                this.entity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                this.entity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

The following sample code is used to control an audio source/slot called “song” that is attached to a Sound entity called “mySound“. The script can be attached to any other entity in the game scene. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            // creates variable for audio entity
            var AudioEntity = app.root.findByName('mySound');
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                AudioEntity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                AudioEntity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/

Graphical User Interfaces (GUIs)

A Graphical User Interface (GUI) provides a way for the game to provide information to the user or to read information from the user. This can be in the form of labels, buttons, text boxes, sliders, menus, and so on. The GUI can sit on top of the actual game. It is always a good idea to design your GUI before making the game – draw up a storyboard or wireframe with the types of GUI controls you want in the game and where you want to place them.

GUIs are created using code and can be added to any object or script in your game. If you have different parts of the GUI on different objects or scripts, it can become confusing and hard to maintain. It is a good idea to have all the GUI parts in one spot on one object.

In order to add a GUI to your scene, you need to add a special method to the script you have created for your GUI which is attached to an object in your scene eg. the camera. The special method that is used to create a GUI is called OnGUI(). This method takes no parameters and returns no data to whatever called it. The method will draw your GUI components on the screen and is called every single frame, just like the Update() method. Different GUI controls (eg. labels, buttons) will have code that goes inside the OnGUI() method.

Labels

Let’s start making a basic GUI that will draw a label with a short message on the screen. Labels display text on the screen that can be a simple string value, a variable value or a concatenated (joined) string and variable value eg. “Score: ” + scoreVariable.

A label displaying the score.
A label displaying the score.

Watch the video on Labels below or scroll down to read the instructions and sample code.

Create a new scene in your project and a new script called myGUI. Attach this script to the Main Camera. Add the following code to your script inside the class but outside of all other methods (i.e. do not place it inside the Start() or Update() methods).

void OnGUI(){
 GUI.Label (new Rect(0,0,80,20), "Hello");
}

Run the scene and you should see ‘Hello’ displayed on the screen in the top left corner. You have just created a basic GUI with a label that draws in the top left corner of your screen (at position 0 on x axis and position 0 on y axis of screen). The label has a width of 80 and a height of 20. The parameters inside Rect() are x position, y position, width, height. The label can display a string value or variable (or concatenated strings/variables).

Boxes

The box is similar to a label except that a box has a dark border around the label. An example of a box is shown below.

An example of a box.
An example of a box.

Watch the video on Boxes below or scroll down to read the instructions and sample code.

The syntax for creating a box is also similar to creating a label. new Rect() takes the parameters of x position, y position, width, and height). An example of a box containing a “Hello” string message is shown below. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(0,0,80,20), "Hello");

If you want a box at the middle-top area of the screen, you can use code like this. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(Screen.width / 2 - 20, 0, 80, 20), "Hello");

Buttons

Buttons can be in one of two states. A button can be either pressed down or not pressed down. An if statement can be used to determine whether a button is being pressed (a boolean value of true or false). If you keep the button pressed down with the mouse, it will not behave differently to just clicking once. The image below shows an example of a button.

An example of a button that reloads/resets the current level in a game.
An example of a button that reloads/resets the current level in a game.

Watch the video on Buttons below or scroll down to read the instructions and sample code.

Like labels and boxes, buttons require an x position, y position, a width and a height value. The sample code below shows how to create a button at an x position of 3, a y position of 3, with a width of 80 and height of 20. When the button is clicked it will reload the level (scene) using Application.LoadLevel. In this example the scene is called ‘myScene’. This code would be placed inside the OnGUI() method:

if (GUI.Button (new Rect (3, 3, 80, 20), "Reset")) {
 Application.LoadLevel ("myScene");
 }

Repeat button

A repeat button is like a normal button except that it can be pressed and held down with the mouse click. It can be used to increase the value of a variable while the button is being held down.

repeat_button

The example below increases a variable’s value while the button is being held down. This code would be placed inside the OnGUI() method:

if (GUI.RepeatButton (new Rect (0, 0, 80, 20), "Increase")) {
 myVariable += 1;
 print (myVariable);
 }

Toggle

A toggle button (also known as a ‘stated’ button because it can be in different states) is like a switch – it can be on or off. It can be used to set something in one state or another. It takes a boolean parameter (whether the button is clicked or not) and returns a boolean value (tells the user if the button is clicked).

The two images below show a toggle in two different states (off and on).

Screen Shot 2015-11-15 at 8.45.02 PM Screen Shot 2015-11-15 at 8.45.14 PM

An example of the code is shown below with a boolean variable called ‘mySwitch’.

bool mySwitch = false;
 
void OnGUI(){
 mySwitch = GUI.Toggle(new Rect(290,20,80,20), mySwitch, "My switch");
 }

Toolbar

A toolbar is a row of several buttons. You can have however many buttons you like on a toolbar, but only one button can be selected at any one time. An integer variable is used to keep track of which button is selected and an array of strings is used for the different buttons.

toolbar

The number of items in the array determines how many buttons there are. For example, if there are three items in the array then there will be three buttons. If the first button is selected, the integer value will be 0. If the second button is selected, the integer value will be 1. If the third button is selected, the integer value will be 2, and so on.

The sample code below shows the integer value variable, the array of strings, and the Toolbar GUI control.

int difficulty = 0;
string[] list = {"Easy", "Medium", "Hard"};
 
void OnGUI(){
 difficulty = GUI.Toolbar(new Rect (0,0,200,30), difficulty, list);
 }

 Textfield

A textfield allows the user to input text. The textfield can display text and also accepts text from the user as they click in the box and type in it. A string variable can be used to store text that is displayed inside the textfield, and then store the text that the user types in.

textfield
The code below shows how a textfield can be added to a scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextField(new Rect(600,20,130,30), textInput);
 }

Textarea

A textarea is just like a textfield except that it can store multiple lines of text.

textarea

 

The sample code below shows how to add a textarea control to your scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextArea(new Rect(600,20,130,120), textInput);
 }

Sliders

Sliders allow the user to select a value between a range of different values by clicking and dragging a slider with the mouse. You can add horizontal and vertical sliders to your scenes in Unity. The slider takes a float value that is used for the default position of the slider, and returns a float value that contains the value the user changed the slider to. It also takes a minimum and maximum slider value.

sliders

 

The sample code below shows how to add both horizontal and vertical sliders to a scene. In the two examples, there are float variables that are initially set to a value of 0 (inside the main class). Each slider takes a float value and then returns a float value. The x and y positions as well as the width and heigh are specified. Parameters for minimum and maximum values for the sliders are also added at the end of the statement – in this example, the minimum value is 0 and the maximum value is 100.

float horizontalValue = 0;
float verticalValue = 0;
 
void OnGUI(){
 horizontalValue = GUI.HorizontalSlider (new Rect (30, 20, 150, 20), horizontalValue, 0, 100);
 verticalValue = GUI.VerticalSlider (new Rect (5, 5, 20, 150), verticalValue, 0, 100);
 }

In the next tutorial we will look at how to customise and style GUI controls.

Accessing other objects and modifying their components

This tutorial explains how you can write a script in C# that can access other objects and then modify their components. In this example, we will attach a script to the Main Camera and then use that script to access a Cube object and modify it’s position, rotation and scale.

Here is the sample code that is attached to the Main Camera and accessing the Cube object.

using UnityEngine;
using System.Collections;
 
public class moveOtherObject : MonoBehaviour {
 
 // this script accesses another object and modifies its components
 // it can be attached to any other object e.g script and is accessing a Cube
 
 // this is the other game object you want to access
 public GameObject target;
 
 // Use this for initialization
 void Start () {
 target = GameObject.Find ("Cube");
 
 }
 
 // Update is called once per frame
 void Update () {
 target.transform.Translate (0f, 0f, 0.1f);
 target.transform.Rotate (0f, 0f, 1f);
 target.transform.localScale = new Vector3 (1.5f, 1.5f, 1.5f);
 
 }
}

Create a rolling ball game with force and gravity

This tutorial will show you how to create a simple rolling ball game using the Rigidbody physics component in unity to add force and gravity. In this game, we will use the W,A,S,D keys to move the ball left and right, and backwards and forwards. We will also use the Space key to make the ball jump up and gravity will bring the ball back down, as seen in the animated GIF below.

rollingball

Watch the video below to see how you can create a simple rolling ball game with force and gravity. Then scroll down to take a look at the sample code.

Here is the sample code in C# for this game.

using UnityEngine;
using System.Collections;
 
// Simple Rolling Ball Game code - 18 Oct 2015 Daniel Wood
// Add this code to a script called 'move' and then attach the script to a sphere in your game
 
[RequireComponent (typeof(Rigidbody))]
 
public class move : MonoBehaviour {
 
 public float xForce = 10.0f;
 public float zForce = 10.0f;
 public float yForce = 500.0f;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 // this is for the X axis' movement (moving left and right)
 float x = 0.0f;
 
 if (Input.GetKey (KeyCode.A)) {
 x = x - xForce;
 }
 
 if (Input.GetKey (KeyCode.D)) {
 x = x + xForce;
 }
 
 // this is for the Z axis' movement (moving backwards and forwards)
 float z = 0.0f;
 
 if (Input.GetKey (KeyCode.S)) {
 z = z - zForce;
 }
 
 if (Input.GetKey (KeyCode.W)) {
 z = z + zForce;
 }
 
 // this is for the Y axis' movement (jumping)
 float y = 0.0f;
 
 if (Input.GetKeyDown (KeyCode.Space)) {
 y = yForce;
 }
 
 GetComponent<Rigidbody> ().AddForce (x, y, z);
 
 }
}

This a simple game with no scoring or other objects to interact with, but you could easily extend the game by adding a user interface, scoring, different cameras, and objects to interact with. As an example, you could make a simple pinball game.

Scripting in Unity with C#

In this tutorial we will look at how to start scripting in Unity using the C# language. Scripts are what are needed to make your game interactive. In addition to the videos on scripting, make sure you also check out the C# Script Reference page where you can find examples of scripting and sample code.

Basic template script

Every script in Unity has a few required components that you need to include. This template script contains the basic components that every script needs to begin with when using C# scripts in Unity.

using UnityEngine;
using System.Collections;
 
public class scriptNameGoesHere : MonoBehaviour {
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
}

This script is made up of three sections:

  • The using section
  • The class declaration section
  • The class contents

The using section

The section of the code lists the libraries that the script will be using. This is usually left as it is and not changed most of the time.

The class declaration section

All scripts contain a class that is named after the actual script. For example, if the script file is called characterMove.cs then the class will be called characterMove. Note that script file names and class names should not contain any spaces. The first line of this section (the class declaration) doesn’t really get changed much so it should be left alone. All of the code that exists between the opening { and closing } brackets is a part of this class. All of your code will go between these opening and closing brackets.

The class contents

The code placed in between the opening and closing brackets of the class is what makes up the script. All of your code goes here. By default, a script will have two methods inside the class, the Start method and the Update method.

Any code that is placed inside the Start method will run when the scene that it is attached to first starts. Any code that is placed inside the Update method will run every single time the game updates which is usually about 60 times a second but this will depend on the computer being used.

Note that statements in C# have a semi-colon (;) at the end of the line. Leaving the semi-colon out can cause errors.

Comments

The // characters are used to add comments to your code. Any text on a line after the two forward slashes will not be treated as code. Comments are useful as they contain notes about what is happening in the code an can help others understand the algorithm.

Here is an example of a comment:

// This is a comment

Now check out the next tutorial: Data Types and Variables in C#.