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!

Step 1
Step 2
Begin by opening Unity!
Step 3
Click the button that says "New Project"
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]

Step 5
Click this button to set the project's location
Step 6
Go into the folder labeled "Dropbox"
Step 7
Select the folder with your name on it and click "Choose" (i.e. "Aaron" - NOT the one called [Your Name] shown here)
Step 8
Make sure "3D' is selected and then click "Create project"
Step 9
You should now have a fresh project that looks like this!
Step 10
Click "Create" in the project menu and select "Folder"
Step 11
Name the folder "_Scenes"
Step 12
Click "File" then "Save Scene as..."
Step 13
Name the scene "MainScene" then click "Save"
Step 14
Drag the "MainScene" into the "_Scenes" folder.
Step 15
In the Hierarchy's "Create" menu, select "3D Object" > "Plane"
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"

Step 17
Now let's create another 3D Object, this time a "Sphere"
Step 18
Set the position of the sphere to the center of our scene by clicking the gear and then selecting "Reset"
Step 19
We can get a good view of our sphere in the scene view by selecting it and pressing "F" on the keyboard.
Step 20
Rename the sphere "Player" and change it's Y position to "0.5" so that it rests on top the plane.
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"




Step 22
That's better, much more space to work with!
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!
Step 24
Select the "Directional Light" in the hierarchy.



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

Step 25
Now our "Main Light" illuminates every object in the scene as shown in this image.
Step 26
Now let's create another "Directional Light"
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!

Step 28
Create a new "Empty" GameObject.
Step 29
Rename this object "Lighting" and reset its Transform.
Step 30
Drag your two lights into this "Lighting" object. Your hierarchy should look like this:
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

Step 32
Create a new folder in our assets directory to hold our scripts.
Step 33
Double click the "Scripts" folder to open it, and create a new "C# Script"inside.
Step 34
Name this script "PlayerController" and double click it to open for editing.
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

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"

  • Step 37
    Attach the "PlayerController" script to the player as shown.
    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!
    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!
    Step 41
    Select the "Main Camera" and move it up by 10 and tilt the angle down towards the ground.
    Step 42
    Your game view should look like this:
    Step 43
    Create a new "C# Script" in the scripts folder and name it "CameraController"
    Step 44
    Add this code to the "CameraController" script. Read the comments!
    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!

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

    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!

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

    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.

    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!

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

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

    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.

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

    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.

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

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

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

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

    Step 62
    Add this code to the "Rotator.cs" script. This will make the cube rotate constantly while the game is running.
    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!

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

    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!

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

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

    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

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

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

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

    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.

    Step 74
    Duplicate the PickUp object

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

    Step 76
    Your scene should look something like this:

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

    Unity Documentation: OnTriggerEnter

    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..."

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

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

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

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

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

    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

    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!

    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.

    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.

    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!


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

    Step 92
    Your game view should now look like this:

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

    Always read the comments!

    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:


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

    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!

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

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

    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.

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

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

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

    Account

    MVCode

    Created By

    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