Learn to Code.

Coding recommendations, web based coding environment, learn coding and robotics.

Create your FREE account now

Roll-A-Ball in Unity 5 (C#)

About this lesson

In this lesson we will learn how to use Unity and C# programming to make a 3D game with a rolling ball as the player and cubes that we can pick up to increase our score!

Concepts Introduced:

Data: Floating Point Numbers
Data type that can be used to store precise decimal values.

Concepts Reviewed:

Conditional
We will use if statements to check boolean conditions before executing code.
Variables
We will use variables to store values such as the score and references to GameObjects.
Booleans
We will use comparison operators to return boolean values (true or false) in our conditional statements.
Show Platform Skills
Unity: GameObject
GameObjects are the fundamental objects in Unity that represent characters, props and scenery.
Unity: Rigidbody
Rigidbodies enable your GameObjects to act under the control of physics.
Unity: Lights
Lights define the color and mood of your 3D environment.
Unity: Transform
The Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform.
Unity: Colliders
We use colliders to determine when two objects make contact in our game.
Unity: Prefabs
Prefabs act as templates from which you can create new object instances in the scene.
Step 1
Temp1427490397
Step 2
Begin by opening Unity!
Temp1426887931
Step 3
Click the button that says "New Project"
Temp1426888102
Step 4
Fill in the "project name" with "Roll-A-Ball" followed by your name in brackets.

Examples: Roll-A-Ball [Aaron] --or-- Roll-A-Ball [Chas]

Temp1426888374
Step 5
Click this button to set the project's location
Temp1426888650
Step 6
Go into the folder labeled "Dropbox"
Temp1426888701
Step 7
Select the folder with your name on it and click "Choose" (i.e. "Aaron" - NOT the one called [Your Name] shown here)
Temp1426888832
Step 8
Make sure "3D' is selected and then click "Create project"
Temp1426889155
Step 9
You should now have a fresh project that looks like this!
Temp1426889566
Step 10
Click "Create" in the project menu and select "Folder"
Temp1426889491
Step 11
Name the folder "_Scenes"
Temp1426889444
Step 12
Click "File" then "Save Scene as..."
Temp1426889640
Step 13
Name the scene "MainScene" then click "Save"
Temp1426889678
Step 14
Drag the "MainScene" into the "_Scenes" folder.
Temp1426889848
Step 15
In the Hierarchy's "Create" menu, select "3D Object" > "Plane"
Temp1426890933
Step 16
Rename the plane "Ground" and make sure the Transform values match these.

To rename an object in the hierarchy, select it and press "Enter"

Temp1426891137
Step 17
Now let's create another 3D Object, this time a "Sphere"
Temp1426892152
Step 18
Set the position of the sphere to the center of our scene by clicking the gear and then selecting "Reset"
Temp1426892270
Step 19
We can get a good view of our sphere in the scene view by selecting it and pressing "F" on the keyboard.
Temp1426892347
Step 20
Rename the sphere "Player" and change it's Y position to "0.5" so that it rests on top the plane.
Temp1426892479
Step 21
You may have noticed that we don't have much space around the player to move. Let's double the size of our "Ground"




Temp1426892734
Step 22
That's better, much more space to work with!
Temp1426893177
Step 23
Take a moment to save your scene AND save your project. Remember to do BOTH every time you want to save, and save OFTEN!
Temp1426893803
Step 24
Select the "Directional Light" in the hierarchy.



Name this directional light "Main Light" and set it up in the inspector as shown.

Temp1427137442
Step 25
Now our "Main Light" illuminates every object in the scene as shown in this image.
Temp1427137611
Step 26
Now let's create another "Directional Light"
Temp1427137725
Step 27
Rename this light "Fill Light" and set it up as shown.

This light illuminates our scene from the opposite angle of our main light, giving the backside of the ball a nice hue.

To change the color of the light, click on the area next to the color property.

Feel free to adjust any of these values as you see fit, or change the fill color. Light the scene the way you want!

Temp1427138069
Step 28
Create a new "Empty" GameObject.
Temp1427138644
Step 29
Rename this object "Lighting" and reset its Transform.
Temp1427138697
Step 30
Drag your two lights into this "Lighting" object. Your hierarchy should look like this:
Temp1427138952
Step 31
We are finally ready to add player movement! First add a "Rigidbody" component to the ball.
(Add Component > Physics > Rigidbody)

Adding a Rigidbody component to an object will put its motion under the control of Unity's physics engine. Even without adding any code, a Rigidbody object will be pulled downward by gravity and will react to collisions with incoming objects if the right Collider component is also present.

Unity Documentation: Rigidbody

Temp1427139257
Step 32
Create a new folder in our assets directory to hold our scripts.
Temp1427139390
Step 33
Double click the "Scripts" folder to open it, and create a new "C# Script"inside.
Temp1427139474
Step 34
Name this script "PlayerController" and double click it to open for editing.
Temp1427139631
Step 35
This C# script will allow us to move the player with the arrow keys (or WASD)

Fill in your script with this code. Read the comments and think about what everything is doing.

  • GetComponent<Rigidbody>( ) refers to the "Rigidbody" component on the GameObject the script is attached to.
  • Adding force to a Rigidbody causes the object with that Rigidbody to move in the scene!

Unity Documentation: Input.GetAxis

Unity Documentation: Rigidbody.AddForce

Temp1427141375
using UnityEngine;
using System;

public class PlayerController : MonoBehaviour 
{

    public float speed = 800.0f;

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

        GetComponent<Rigidbody>().AddForce (movement * speed * Time.deltaTime);
    }

}
Step 36
Let's make sure we understand how this script works. Take a look at the same script coded in JavaScript.
Key differences to note:

    • When creating a variable, instead of using "var" we specify the type of the variable

      JavaScript has types also, you've probably seen 'integers', 'strings', and 'booleans'. In JavaScript, you don't need to specify the type of variable, but operations are specific to variable types. For example, you cannot do "hi" * "bye" but you can do 7 * 8

    • Instead of placing the word "function" before the name of a function, you place the type of value that you want the function to return before the name of a function.

      In this case, FixedUpdate() doesn't return anything, it just acts on elements that we view in our scene. Therefore, the return type is "void"

    Temp1427142364
  • Step 37
    Attach the "PlayerController" script to the player as shown.
    Temp1427141809
    Step 38
    Enter play mode and test. You should now be able to roll the ball around the plane!
    Step 39
    If you want the ball to move faster or slower, play around with the "Speed" variable!
    Temp1427143917
    Step 40
    Take a moment to save your scene AND save your project. Remember to do BOTH every time you want to save, and save OFTEN!
    Temp1427488120
    Step 41
    Select the "Main Camera" and move it up by 10 and tilt the angle down towards the ground.
    Temp1427145955
    Step 42
    Your game view should look like this:
    Temp1427145980
    Step 43
    Create a new "C# Script" in the scripts folder and name it "CameraController"
    Temp1427146647
    Step 44
    Add this code to the "CameraController" script. Read the comments!
    Temp1468459858
    using UnityEngine;
    using System;
    
    public class CameraController : MonoBehaviour 
    {
        public GameObject player;
        Vector3 offset;
    
        void Start () 
        {
            offset = transform.position;
        }
    
        void LateUpdate () 
        {
            transform.position = player.transform.position + offset;
        }
    }
    Step 45
    Let's take a look at the same code in JavaScript.

    Notice that they look very similar. The only differences in the syntax are in the variable and function definitions!

    Temp1427147750
    Step 46
    Attach the "CameraController" to the "Main Camera"
    Temp1427147858
    Step 47
    You should see this slot for a GameObject in the inspector. Drag the "Player" to this slot from the hierarchy.
    Temp1427148153

    Step 48
    Enter play mode and test. Your camera should follow the player, so the ball will remain in the center of the screen!
    Step 49
    Take a moment to save your scene AND save your project. Remember to do BOTH every time you want to save, and save OFTEN!
    Temp1427488212

    Step 50
    Now we need some walls to keep the ball on the plane. Start by creating a new "Cube"
    Temp1427148405

    Step 51
    This will be the "Right Wall"

    Rename the cube "Right Wall"

    Set up the wall's Transform as shown.

    Look at how the wall appears in the scene.

    Temp1427149139

    Step 52
    Duplicate the "Right Wall" three times and make small changes to each of their Transforms to make the rest of the walls.

    HINT: The left wall should be fairly straightforward, the top and bottom walls will require some rotation!

    Temp1427148820

    Step 53
    When you are finished you should have a platform with four walls that looks like this:
    Temp1427149314

    Step 54
    Make a new empty GameObject. Name it "Walls" and reset its Transform, then place the four walls inside.
    Temp1427398873

    Step 55
    Now we are ready to make some objects that we can pick up! Create a new "Cube" from the menu in the hierarchy.
    Temp1427399139

    Step 56
    Rename the cube "PickUp" and reset its Transform.
    Temp1427399739

    Step 57
    Deactivate the "Player" temporarily by unchecking the box in the inspector next to its name.

    This is just so we have a better view of our PickUp cube while we set up its properties.

    Temp1427400084

    Step 58
    Set up the Transform of the "PickUp" as shown.
    Temp1427400214

    Step 59
    Your "PickUp" object should now appear like this in the scene view.
    Temp1427400267

    Step 60
    Open the "Scripts" folder in the project window and create a new "C# Script"
    Temp1427400417

    Step 61
    Name this script "Rotator" and open it for editing.
    Temp1427400460

    Step 62
    Add this code to the "Rotator.cs" script. This will make the cube rotate constantly while the game is running.
    Temp1427400903
    using UnityEngine;
    using System.Collections;
    
    public class Rotator : MonoBehaviour 
    {
    	void Update ()
    	{
    		transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime);
    	}
    }

    Step 63
    Let's look at the same code in JavaScript.

    Notice the key difference between these very similar scripts!

    Temp1427401108

    Step 64
    Select the "PickUp" object and attach the "Rotator" script to it.
    Temp1427401347

    Step 65
    Enter play mode and test. You should see your PickUp cube rotating like this:
    Step 66
    Take a moment to save your scene AND save your project. Remember to do BOTH every time you want to save, and save OFTEN!
    Temp1427488300

    Step 67
    Create a new folder in our project window called "Prefabs"
    Temp1427401667

    Step 68
    Drag the "PickUp" object from the hierarchy into the "Prefabs" folder.
    Temp1427401840

    Step 69
    You should now have what is called a "Prefab" of your PickUp cube.

    Prefabs are a powerful tool in Unity. The prefab acts as a template from which you can create new object instances in the scene. Any edits made to a prefab asset are immediately reflected in all instances produced from it but you can also override components and settings for each instance individually.

    Unity Manual: Prefabs

    Temp1427401999

    Step 70
    Create a new empty GameObject, name it "PickUps" and reset its Transform. Then place the existing PickUp inside it.
    Temp1427404029

    Step 71
    Set the Y position of the lighting parent object to 50 to move them out of the way.
    Temp1427404276

    Step 72
    Rotate the scene so you have a top-down view of game like this:
    Temp1427404310

    Step 73
    Select the PickUp object and click the button that says "Local."

    The button should now say "Global" as seen here, and you will see only two arrows on the PickUp cube in the scene.

    Temp1427404499

    Step 74
    Duplicate the PickUp object
    Temp1427406635

    Step 75
    Continue duplicating the PickUp object and move them around the plane by dragging the two arrows for X and Z.
    Temp1427407063

    Step 76
    Your scene should look something like this:
    Temp1427407299

    Step 77
    Open the "PlayerController" script for editing and add this code. Make sure to read the comments!

    Unity Documentation: OnTriggerEnter

    Temp1427407895
    void OnTriggerEnter(Collider other)
    {
    	if (other.gameObject.tag == "PickUp")
    	{
    		other.gameObject.SetActive(false);
    	}
    }

    Step 78
    Now we need to create the "PickUp" tag. Click the dropdown menu next to where it says "Tag" and select "Add Tag..."
    Temp1427408043

    Step 79
    Click the "+" to add a new tag.
    Temp1427408102

    Step 80
    Name this tag "PickUp" (pay attention to capitalization)
    Temp1427408143

    Step 81
    Select the PickUp Prefab and tag it as "PickUp"
    Temp1427408510

    Step 82
    Through the power of prefabs, all of our PickUp objects are now tagged as PickUp!
    Temp1427408587

    Step 83
    Reactivate the "Player" by checking this box.
    Temp1427408669

    Step 84
    Enter play mode and test. You may notice that you can't actually pick up the cubes yet!
    Step 85
    Select the PickUp Prefab and check the box next to "Is Trigger" to make the collider into a "Trigger Collider"

    Unity Documentation: Is Trigger

    Temp1427408909

    Step 86
    Try it out now!
    Step 87
    Take a moment to save your scene AND save your project. Remember to do BOTH every time you want to save, and save OFTEN!
    Save scene and project

    Step 88
    We can pick up cubes, but we don't keep track of the player's score! Let's create a UI Text object to display the score.
    Temp1427418812

    Step 89
    Rename this object "ScoreText" and change the Text displayed to "Score: 0"

    Notice where the text appears on the screen in the game view. We will need to adjust this.

    Temp1427486441

    Step 90
    Let's place the text in the top left corner.

    1. Click on the box of anchor presets

    2. Select "top left"

    3. Adjust the X and Y position

    For more information on Unity's UI system click here!


    Temp1427486866

    Step 91
    Increase the font size to 24 and change the color to white.
    Temp1427487072

    Step 92
    Your game view should now look like this:
    Temp1427487093

    Step 93
    Open up "PlayerController" for editing and add the following code.

    Always read the comments!

    Temp1427487888

    Step 94
    float vs. int

    You may be wondering about the difference between a "float" and an "int"

    They are both data types that store numbers, but there is a key difference:

    This distinction is important because the two types are incompatible when it comes to mathematical operations. For example, if we try to multiply an int by a float, we get this error:


    Temp1430506759

    Step 95
    Select the "Player" and assign the "ScoreText" object to the new slot we have in the inspector for "Score Text"
    Temp1427488080

    Step 96
    Enter play mode and test!
    Step 97
    Let's add a new Text object that we can use to display the message "You Win!" when all of the cubes have been collected.

    Practice using the UI Text object by setting it up on your own!

    Name this object "WinText"

    We want to use the "middle center" anchor with center justified paragraph alignment.

    Increase the height of the "Rect Transform" if needed to fit your chosen font size.

    Make the text any color you want!

    Temp1427489108

    Step 98
    If you are having trouble, here is what mine looks like:
    Temp1427489164

    Step 99
    Deactivate the "WinText" so we can wait to activate it until we collect all of the cubes.
    Temp1427489417

    Step 100
    Open the "PlayerController" for editing.

    Use what you have learned to determine where to place these two pieces of code to make our winText function properly!

    Remember: Your total number of cubes may not be 16.

    Temp1427489775
    public Text winText;
    --------------------------------------------------
    if (count >= 16) 
    {
    	winText.gameObject.SetActive(true);
    }

    Step 101
    Remember to assign the "WinText" object to the appropriate slot!
    Temp1427490014

    Step 102
    Congratulations! You have completed your first 3D game in Unity!
    Step 103
    Remember to save your awesome new game!
    Save scene and project
    Roll-A-Ball in Unity 5 (C#) Info

    Account

    MVCode Clubs

    Created By

    Mvcc logo new aaron

    Access Level

    public

    For Teachers and Schools

    Teach coding to your students with MVCode Teach

    MVCode offers an integrated product designed to teach coding to students.

    Learn more about MVCode Teach

    Create an MVCode Account
    • Learn to code
    • Save your progress
    • Course and Lesson recommendations
    • Participate in the MVCode community

    Create your FREE account now