Unity Tutorial

Before We Begin..

Resources
Before we get started, just a reminder that in addition to this tutorial, Unity has TONS of learning resources available such as:

Tutorials and Live Training: http://unity3d.com/learn
Manual: http://docs.unity3d.com/Manual/index.html
Scripting API Documentation: http://docs.unity3d.com/ScriptReference/
Q&A Help: http://answers.unity3d.com/

Lynda
In addition to these resources, being a student at SFU gives you access to a great site for learning called Lynda.com
Lynda has all sorts of tutorials including Unity tutorials

http://www.lynda.com/member.aspx
As lynda is usually a paid service, to watch the tutorials, you must access lynda through SFU
http://cufts2.lib.sfu.ca/CRDB4/BVAS/resource/10456

I highly encourage you to take advantage of all these great learning resources

Completed Project Download Link
Also, here's a download link to the Completed Unity Tutorial Project File so if you can't figure out how to do something, just check out the completed project!
https://dl.dropboxusercontent.com/u/32740967/New%20Unity%20Project%201.zip

Anyways… Let's get started!

What Unity Is/Isn't

We will start off by learning a bit about Unity and its features. We won't start making games right away, but don't worry, we'll get to that soon!
IS

  • A Game engine
    • Flexible application used to make a wide variety of different kinds of games
  • - To make games
  • - To piece different assets together into one whole

Isn't

  • A level editor
    • Games often need an external programs to help make assets used to build levels for the game
    • that being said, there are lots of built in tools which help us
    • Unity CAN be used to piece together different parts of your level that are made in other applications such as 3d models
    • There are plugins available that allow you to create assets levels more easily from within Unity
  • A 3d modelling application
    • Unity has tools to work with and alter 3-D models, but is not built to create detailed models from scratch
  • An app creation tool
    • Although this is possible, but not ideal

Editor

Let's take a look at the different features that Unity has to offer. We will be spending a lot of time piecing together our game in the Unity editor, so it important to know what everything does.

  • Scenes vs projects
    • Projects are like games
    • Scenes are like levels

Interface

  • Different windows
    • Scene View
      • Window where you can view, edit, and navigate the game world
    • Game View
      • Shows what the camera(s) in your game will see. Displays the game as it will look
    • Hierarchy
      • All the assets being used in the game and their properties
    • Inspector
      • Gives details and properties of a gameobject, material, shader, etc…
    • Assets Window
      • All the assets or "pieces" in your game. Things like 3d models, textures, sprites
      • It is VERY important to keep your assets organized in folders such as "scripts", "textures", "models", etc… so you don't get lost
    • Console
      • Used for displaying information about any warnings or errors or for debugging in your game *
  • Creating different layouts
    • Rearrange, resize windows however you like
    • Save and load custom/preset layouts using the drop down menu in the top right corner

Navigation

  • Scene view
    • Left click/drag to select things in the scene
    • Right click and move mouse to look around
    • Click down mouse wheel to pan the camera
    • Rotate mouse wheel to zoom in and out
    • Alt + right mouse is zoom in and out
    • Alt + left click is rotate around a point
    • Ctrl + alt + f = move selected object to view
    • Double clicking an object will focus the camera on it or edit->focus
    • 2d/3d toggle
    • Isometric/perspective toggle (isometric = representing 3d objects in 2d)
    • Different angles x y z

Settings

  • Build settings
  • Project settings
    • Input and player settings
  • Render settings

The Basics of Working With Unity

In order to work with Unity, we need to know what things are. Things like gameobjects, components and prefabs are used everywhere in Unity, so it is important that you know what each thing means and how to use it.
Gameobjects

  • Like containers
  • Containers for components

Components

  • Little bits of functionality for a gameobject
  • you can view the components of a gameobject in the inspector when the gameobject is selected

Parenting

  • Makes a gameobject follow the other
  • The coordinates of the child object are now based on that of the parent object (its local coordinates)

Prefabs

  • Pre created objects
  • Example: a cube
  • Make your own by dragging an object you've made from hierarchy into the assets directory

Important components

  • Rigidbody
  • Colliders

Important Gameobjects

  • Cameras
    • Main camera
      • The camera your gameview currently sees when you start unity.
        • orthographic - has no perspective
          • Used in 2-D games mostly
          • "zooming" in and out is controlled by changing the orthographic size
        • perspective - has perspective
  • GameManager
    • An object created by the user to manage the game, levels, things like that
  • Player

Different coordinates/spaces in unity

  • world space - coordinates of objects
  • viewport space - x, y from 0 to 1 starting in the bottom left corner
  • screen space - pixels on the screen

Scripting

  • How to add functionality to the game
  • Like making your own component on a gameobject

Actually Working With Unity

Okay, so we now know what Unity is and some definitions for things. Now lets experiment a bit and see how these things actually work by making a First Person Shooter game with some pre-built game objects or "prefabs".

  • Assets->import->character Controllers
  • Drag first person controller onto scene view or hierarchy
  • Gameobject create plane
  • move first person controller overtop the plane and hit the play button
  • Explore the components of charactercontroller changing values in the inspector and experiment with parenting
  • Explore changing variables in the scene view while game is running and while it is not
  • While game is running, you can change variables, but the changes will not be saves once you stop playing
  • If you change the variable while the game is stopped, it will stay that way.

Let's add a simple light

  • directional lights.
    • lights up scene based on rotation not position.
    • try changing properties in the inspector like the colour

Terrain

  • Assets->import->terrain assets
  • Delete plane and replace it with terrain
  • Explore terrain script tools
    • Raise/lower terrain
    • Paint textures
    • Paint trees

Creating a GameObject From Scratch
Now that we have an idea of how to piece assets and gameobjects together, lets try making our own game without using any pre-made things. We're going to make a simple game where we control a player's movement from a top-down view and dodge enemies that are bouncing off walls around us.

  • Make a new scene
  • Make a new empty gameobject

Add components

  • Mesh filter
    • Holds our 3d mesh.
  • Mesh renderer
    • Determines how our 3d mesh will render
  • Rigidbody
    • For physics
  • Collider
    • For collisions
  • Add Mesh filter and Renderer
    • Choose cube as the mesh filter mesh
    • it does nothing when we hit play except look pretty
  • Add rigidbody component
    • Now the cube uses physics
    • But it just keeps falling
  • Add box collider
    • Now it hits the ground and doesn't go through it
  • Make the main camera a child of the Player
    • Drag the main camera overtop of the Player in the game hierarchy
    • Camera will now follow the player around
    • Position camera to have a top down view of the world
  • Now let's make our own components
    • Add new C# script component
    • Call it PlayerController

Scripting

  • Like making your own component
  • Useful function calls:
    • Start()
      • code is executed the very first frame the object is instantiated
    • FixedUpdate()
      • Updated every physics update
    • Update()
      • Updated every frame
    • OnCollisionEnter(Collision collision)
      • Called when two colliders collide
  • Data types
    • Floats
    • ints
    • Vectors
  • Other useful stuff
      • instantiate()
      • Documentation
        • highlight something in mondevelop then use (ctrl + ') to search for it
    • Classes
    • Inheritance

Building PlayerController

public float speed
void FixedUpdate()
{
    float moveX = Input.GetAxis ("Horizontal");
    float moveY = Input.GetAxis ("Vertical");
    Vector3 move = new Vector3 (moveX, 0, moveY);
    rigidbody.velocity = move * speed;
}
  • FixedUpdate() is a function that is called once every physics update. It is used to do physics related stuff.
  • Since our gameobject has a rigidbody attached, we are using FixedUpdate()
  • Speed is a public float variable that will affect the speed our player moves at
  • If we Debug.Log( Input.GetAxis)
    • We can see the numbers it returns
    • Floats from -1 to 1
  • In input settings, you can adjust the behaviour of Input.GetAxis
  • When we add the speed public variable to the class, notice that it appears in the editor
    • its value can be changed from the editor now
    • While in play mode, the value of the variable can be changed, but will revert back to what it was before once you've stopped playing
    • This can be useful for testing
    • To actually change the value of the variable, you have to do so while the game is stopped

Building the EnemyAI

  • Make a new cube
    • Scale it down to half the size of the player
  • Add a rigidbody
  • Add a new script
    • EnemyAI
  • Declare
    • public float speed
    • Private Vector3 direction
  • In the Start() function
private Vector3 direction;
public float speed;
void Start()
{
    direction = new Vector3 (Random.Range (-1f, 1f), 0, Random.Range (-1f, 1f));
    rigidbody.velocity = direction * speed;
}
  • In the FixedUpdate() function
void FixedUpdate()
{
    rigidbody.velocity = direction * speed;
}
  • In the OnCollisionEnter(Collision collision) function
void OnCollisionEnter(Collision collision)
{
    //reflect the speed and direction of enemy when it collides with a wall
    ContactPoint contact = collision.contacts [0];
    direction = Vector3.Reflect (direction, contact.normal);
}
  • This function is called when another gameobject's collider enters the enemy's collider
  • There are better ways to do reflections in Unity, but this will do for our purposes.

Player Hit Detection Script

  • Add a new script to the player
    • Call it PlayerHit
  • In the OnCollisionEnter(Collision collision) function
void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.tag == "enemy")
    {
        Debug.Log ("Bye");
        Destroy(gameObject);
    }
}
  • Tag the enemy as enemy in the editor

Final touches

  • Let's make the enemy a prefab
  • Drag it into the assets window
  • Now we can make a bunch of copies of it by dragging into the scene window
  • We can also add colours to our gameobjects by making materials with specific colours and changing our MeshRenderer's material to that colour
  • By changing the colour of the prefab, you change all the instances of the object in your scene!
  • Or we can make a script that would randomly assign colours to things. Ex:
void Start () 
{
    Color newColor = new Color (Random.value, Random.value, Random.value, 1.0f);
    renderer.material.color = newColor;
}

If time allows…

  • Challenge: let's make a Game Over Screen
  • See if you can do this by yourself!
  • Hint: create a new scene that displays a gameover screen then see if you can make unity switch the current scene to the "Game Over Scene" when the player gets hit.
  • use the scripting API to find functions that might help with switching scenes
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License