Diving into Development - OUYA Game Development by Example Beginner's Guide (2014)

OUYA Game Development by Example Beginner's Guide (2014)

Chapter 3. Diving into Development

In the last two chapters, you familiarized yourself with the Unity development environment and had a taste of what you can create for the OUYA. Now it's time for the fun part: creating code that turns your ideas into mechanics. In this chapter, you'll create your first functioning prototype and write some basic code to see action on the screen. In doing this, you'll cover basic gameplay scripting techniques and some introductory programming in the C# language. We'll also look at the tools provided to us in the Unity API.

Specifically, we'll cover the following topics:

· Setting up a scene in Unity

· Navigating the scene in your workspace

· Lighting and cameras

· Adding scripts to objects

If you're already familiar with Unity and the fundamentals of scripting in C#, feel free to advance to the next chapter; nothing in this chapter is built upon in future chapters, it's only for getting you up to speed with the basic tools we'll be using.

Creating a 3D text prototype

We're going to build a simple 3D text prototype that changes color when triggered by user input. To begin with, either create a new project configured for the OUYA (as demonstrated in Chapter 2, Installing Unity and the OUYA ODK) or simply use the project that you created while following along with this book.

Time for action – manipulating the scene

When you've opened your project, you'll notice that there's only one object in your Hierarchy menu by default; the Main Camera object, which projects the game screen. Now perform the following steps:

1. Select that camera by clicking on it in the Hierarchy menu once. While the camera is selected, you can see an outline of its view plane in the Scene window.


Think of the camera in Unity as a cameraman on a movie set. Everything he sees ends up on the screen, and if something is out of his view, it doesn't make it into the movie. As a developer, you can see everything in your Unity scene at all times, but when you publish your game, the player will only be able to see what the camera captures. Don't worry about this yet—we'll get into camera programming later.

Time for action – manipulating the scene

You'll also notice that while the camera is selected, there are three colored arrows pointing in different directions from the camera's origin. These arrows represent the three axes of position in the game world.

2. Click-and-drag on these arrows to move the camera back and forth on their respective axes. If you grab the camera from the center cube, you can move it across all three axes at the same time. All other game objects can be moved with this same method.

Notice the values in the Inspector window while you drag the camera. As you move it through the game world, its coordinates update in the Transform pane. Alternatively, you can enter a set of coordinates manually into the position axes, and the selected object will move to those coordinates in the scene.

Time for action – manipulating the scene

Moving objects in your scene isn't too helpful from just a single perspective, so Unity has keyboard controls to navigate all dimensions of your scene.

To enter the navigation mode, hold down your right mouse button while your cursor is over the Scene view. You can move the mouse while the button is held down to look around, or use the W, A, S, and D keys to move forward, left, backwards, and right, respectively. You can also move upwards with the E key and downwards with the Q key. If you wish to move faster at any time, holding down the Shift key will increase your speed.

Moving around in an empty world isn't going to do anything for us, so let's add some objects to the scene. Before we can see any physical object clearly, we need to light the scene, so a light will be the first object we add.

3. At the top of your Hierarchy window, there's a button labeled Create. Click on it and select Directional Light from the drop-down menu. Your light will then appear in the Hierarchy and Scene views, with outlines to show the orientation of the light.

We picked a directional light because it's a simple and fast way to light any scene, but there are four main types of lights in Unity that offer their own uses. They are as listed in the following table:


Light type


Directional Light

This shines light universally in a certain direction. The position of these lights in a scene doesn't matter because they illuminate the entire scene evenly, but the angle changes the way the light hits the scene.

Point Light

This emits light from a single point in all directions. Their rotation doesn't matter because the light is emitted evenly from the origin, but the position compared to other objects in the scene affects how strongly it lights them.


This projects a cone of light from an origin towards a certain direction. Rotation and position both matter because the luminosity and orientation angles are both finite.

Area Light

Area lights shine in all directions to one side of a plane and are typically used to light scenes with realistic detail. Currently, they are only available with an upgrade to Unity Pro, and you will not need to use them throughout the course of this book.

Each light also has its own individual properties that can be changed in the Inspector menu. These properties include Color, Intensity, Shadow Type, and so on. Once you've set up a scene, don't be afraid to play with light settings and watch the game world change in real time in the Scene window.

You now have an empty, lit world and you're ready to fill it with physical objects.

4. Go back to the Create button at the top of the Hierarchy window and select Plane. Set every position axis to 0 in the Inspector window so that the plane is in the middle of the scene, and then set your camera's X, Y, and Z position axes to 0, 2.5, and -10 so it has a good view of the plane we placed.

When you're finished, your environment should look something like as shown in the following screenshot (your Scene view will vary based on where you positioned it):

Time for action – manipulating the scene

What just happened?

Thoroughly remember the steps you just performed, because it's how you'll start every project in Unity. Cameras and lighting may not be things we actively notice in games, but they're of paramount importance in Unity. Without them, everything we'd see would be dark or out of the frame, which isn't a suitable stage for your creations.

Time for action – creating and scripting 3D text

To demonstrate basic object properties in Unity, we'll create a 3D text object, which is a kind of game object that displays a string of text at a point in 3D space. The positions of all game objects are specified in X, Y, and Z coordinates, and each coordinate can be changed individually in the Inspector window. Now, perform the following steps:

1. Open the Create menu and select 3D Text to create a New Text object.

2. Use the Inspector window to position it at 0, 5, and 0, and then set the Anchor dropdown to middle center and the Alignment dropdown to center.

This puts your text directly in the center of the scene, elevated above the plane. The default text is Hello World, which is a common filler phase that developers enter when they are first testing text and display. This can be changed to any text you enter in theInspector window under the Text Mesh pane.


Every object inspector window is an aggregation of all the object's components, which are organized into panes. Most objects share some components, such as Transform (position) and Mesh Renderer (appearance), but additional components are the ones that define an object's attributes and abilities.

Any displayed text in Unity can also be changed while the game is running by attaching a code script, which is what we'll do next. Make sure your scene is still positioned in the way we placed it previously, which should look as shown in the following screenshot through your Game window's main camera view:

Time for action – creating and scripting 3D text

Now is a good time to save your progress before we start writing code.

3. Click on File and then Save Scene. The default save location will be your project's Assets folder, but it's a good practice to keep your Assets folder organized into subfolders, so create a new folder called Scenes and save your scene within it as 3dtext. Your new folder will immediately appear inside your Project window below the Assets folder, with your scene inside.


Saving your scene isn't the same as saving your project; your project's saved files only store information about where different component files are stored (assets, scripts, and so on), while your scene's saved data tells the engine how everything is actually positioned within the scene. Think of your project files as useful information for your operating system, and your scene files as useful information for Unity.

Your scene is set up, saved, and ready for scripts, so we'll now begin coding by creating a C# script that controls the color of the text object.

4. Right-click on your Assets folder and create another subfolder called Scripts.

5. Right-click on the Scripts folder, move your mouse over Create, and select C# Script from the drop-down menu.

By creating files from a folder's Create menu, they'll be created within that folder automatically.

6. Name the script ColorChanger and double-click on it to open it in your code editor.

Before we start adding code to the script, we'll do a quick explanation of the anatomy of a script, including all of the important keywords that you need to know and what they mean.

The first two lines of the script that begin with the using keyword denote the code libraries that this script relies on. Just below these is your script's class definition, which gives the code compiler basic information about the script.


Keep in mind that your class name needs to match the script name in order for Unity to load it correctly. If you rename the script file from the Project window or manually in your filesystem in the future, the class name won't update automatically within the script, so make sure they match in order to avoid getting an error.

The public keyword means that other scripts can interact with this one, and the MonoBehavior keyword is the name of the built-in script this one inherits basic properties from. The bracket after the inheritance keyword and the bracket at the very end of the script encapsulate the entire class, and most of your code will be contained between these brackets. It is possible to write code for a class in a separate script if the situation calls for it, but you won't need to do that for the projects in this book.

Every Unity script has two functions already defined in the code when you create it: the Start function and the Update function. Functions are blocks of executable code that can be called to run by the game engine. The Start function is automatically called when an object with this script attached first enters the scene. The Update function is called for every frame, which is extremely quick (typically around 60 times per second), and it manages how the scripted object changes over the passage of time. There are several other built-in functions in Unity's API that can be extended in code by adding the function to a script, and you can create functions from scratch that execute your own code as well.

Both of your starting functions have plain English descriptions written above them. The compiler doesn't interpret these descriptions, but they can be helpful for the programmer to keep notes; any text can be marked as a comment by inserting two forward slashes before it.

Notice that each of the pre-existing functions have parentheses and brackets directly after their names and the word void before them. The word before the function name represents the type of data that the function can return to; void means it won't be sending any data back to the caller. Other common return types include int (integer number), bool (true or false), and string (readable text).

The parentheses after the function name serve a purpose similar to the return keyword, but in the opposite direction; whatever is inside the parentheses denote data that must be sent to the function from the caller. The two pre-existing functions don't have anything inside the parentheses because they don't require data to be passed to them to function.

Lastly, the brackets after the input parameter parentheses are the boundaries of the function. All code that the function contains goes between these two brackets, almost always separated by several lines. Right now, the brackets don't have anything inside of them, and that's what we're going to fill in now.

7. Write a new line, as shown in the following code, with an explanatory comment in your Start function that will change the color of the text material to red:

8. void Start ()

9. {

10. //change the object's color to red

11. gameObject.renderer.material.color = Color.red;



Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The preceding line of code refers to gameObject, which represents the object that we attached the script to. It then points to renderer, a component of said object, and changes the rendered material's color to the standard Color.red. Each line of non-commented code is terminated with a semicolon to tell the compiler to move on to the next line. Make sure each statement ends with a semicolon to avoid compiler errors.


You're not expected to know these commands and keywords already; even if you've had experience with C#, coding in Unity is unique to the engine. You'll develop a natural memory of different code elements in Unity, but if you ever forget something, the Unity web documentation contains every function and keyword in the API.

Save your code in the File menu of your code editor to make sure all of your additions to the script were applied. The code will do what we want it to, but it still doesn't know which object we want to run it on; link the code file to your 3D text object by dragging it from your Project window onto the text object in your Hierarchy window. Alternatively, you can click on the Add Component button at the bottom of the item's Inspector window and find the ColorChanger script under the Scripts tab. If you select the text object, you'll see that the script is a newly added component in the Inspector window.

Press the play arrow button (seen in the following screenshot) at the top of the Unity editor window to see your scene in action. The play button is useful because you can test right in the editor without having to deploy to the console. As soon as your game starts, your 3D text object will turn red according to the script we attached to it.

Time for action – creating and scripting 3D text

What just happened?

You're on the road to code! Every script in Unity is created from a basic template in the Project window, edited in a code editor, and linked to an object in your Hierarchy window by clicking-and-dragging. Scripts can be applied to any number of objects, but be careful that you don't attach scripts to objects that lack the attributes the code looks for. For instance, if you were to try to change the color of the camera, the engine would return an error, because the camera isn't a visible object, and thus doesn't have a renderer.


The names of functions and variables that you create are completely up to you, but many programmers follow a few common conventions to avoid confusion. In the Unity API, variables are camel case (first word all lowercase, first letter of all following words capitalized, as in mainPlayerPosition). Unlike variables, every word in function names is usually capitalized, as in MovePlayerForward().

Have a go hero – flexing your new muscle

Now that you've got the basics down, play around with your new talent. A large part of programming and game development is finding out what works for you and what doesn't. Change small things at first as you start to learn the natural flow of coding, and make bigger changes if it starts to seem too easy. Here are some ideas to get you started:

· Explore the different available colors

· Attach your ColorChanger script to the plane object

· Explore the different attributes that your editor's code hinting suggests

· Add a function to the script by copying the built-in function format

If you develop a taste for exploring on your own, look over some of the beginner topics in online question/answer forums on the web, such as www.stackoverflow.com.

You can also learn straight from the source by following Unity's beginner tutorials, found at http://unity3d.com/learn.

Creating a custom function

The Start function of any script is great for initializing the object's first values, but most scripts rely on several custom functions that get called more than once, and potentially many times.

Time for action – writing a function

In this tutorial, you'll begin writing your own functions and calling them to be executed. Perform the following steps to write a function:

1. Create a new script in the same way you created the color-changing script, but name it ObjectMover. Open the script and add the function declaration named MoveObject below the declaration for Update, so that your full code file appears as shown in the following code:

2. using UnityEngine;

3. using System.Collections;


5. public class ObjectMover : MonoBehaviour

6. {

7. //use this for initialization

8. void Start ()

9. {


11. }


13. //Update is called once per frame

14. void Update ()

15. {


17. }


19. void MoveObject ()

20. {


22. }


You've now declared a brand-new function, as simple as that.

23. Next, add the following line of code that will make it move positively along the x axis (to the right) by two units:

24.Void MoveObject ()


26. gameObject.transform.Translate(2.0f, 0.0f, 0.0f);


The parentheses at the end of this line tell us that a function is being called, and the information inside of them is what's required for that function to run. In this case, we're calling the Translate function, which receives three numeric values that are each applied to the x, y, and z axes of the object we're moving. If we tried to call this function without those parameters, we would receive an error.


When we edited the color of the text, we didn't need to call a function because we could just assign our color value directly to the attribute. More complicated procedures such as moving an object through 3D space require a function to serve as a list of steps in a process. We can assign a value to an attribute by simply using the equal to sign that has the new value after it, but if you're calling a function, you must include the parentheses and the required parameters.

Our MoveObject function is ready to go; all we need to do is call it. The Start and Update functions run automatically, but other functions need to be called for execution. Fortunately, because the Start function runs automatically, we can have it call our new function.

27. Add the following call to your Start function:

28.Void Start ()


30. MoveObject();


Save your changes and attach your new script to your text object. The ObjectMover script has now been added as a component in addition to the ColorChanger script, and we put a function call for it in the Start function so that it will be called as soon as it's loaded.

31. Click on the play arrow button at the top of the editor window to see your new function in action, as shown in the following screenshot:

Time for action – writing a function

As expected, the text immediately moves two units to the right and creates a visible offset from the center of the plane. We don't see movement because we haven't programmed any animations or gradual changes yet; we only have a function that moves text immediately and is called once. But what if we were to call it twice?

32. Edit your Start code to call the MoveObject function again, as shown in the following code:

33.Void Start ()


35. MoveObject();

36. MoveObject();


If you save your changes and run it, you'll see that the distance the text moves has doubled, because we ran the same operation twice.

As you can see in the following screenshot, the text has moved further on the screen than when we called the function once:

Time for action – writing a function

Functions can be called as frequently or as infrequently as you want, and it's good practice to write your functions in such a way that calls to it would apply in several situations, so that you don't have to write multiple overly specific functions.


Object-oriented programming (OOP) is a programming practice that partly involves writing code that can be reused as much as possible. Having broad functions that handle many situations well can save a lot of time and effort.

Next, we'll add some functionality to the script's Update function. So far, we've only made calls from our Start function. The Start function only runs once, so we can't see any changes from it. The Update function that we've been seeing gets called once per frame, and we can use that frequency to simulate real-time passing.

37. Remove both calls to MoveObject from the Start function and put one call in the Update function, as shown in the following code:

38.void Update ()


40. MoveObject();


If we were to run this program right now, our 3D text would be out of the frame before our eyes could even see it; calling that function twice was enough to create an obvious visible difference, but in the Update function, it would be called twice in a fraction of a second.

41. To compensate, let's decrease the amount that the text is moved by 0.01f units using the following code:

42.Void MoveObject ()


44. gameObject.transform.Translate(0.01f, 0.0f, 0.0f);


If 0.01f seems small, that's because it is, but it will add up very quickly if it's called for every frame, and the movement will appear smooth because it's so subtle.


The f character found after the parameter values of the Translate function denotes a float or floating point number. Unlike an integer, floats can hold numbers with decimals. C# requires the f character after every float, and the code will cause an error if it's omitted.

Press the play arrow button and observe the text moving along the x axis by 0.01 units every frame or approximately 60 times per second. Most animations, gradual motions, and timings in games are programmed with frame-by-frame functions, so remember to consider this when creating your mechanics.

What just happened?

By writing your own function from scratch in the ObjectMover script, you've begun to dictate the behavior of any object that it's attached to. Most of the functionality in your games will be written with your own functions, but the built-in Start function lets you call things from the start of the game, and the Update function lets you keep things moving every frame.

Time for action – capturing data with return values

What's on the outside of your functions matters just as much as what's on the inside. Optimizing the amount of information passed around between functions ensures that you'll never find a bridge that you can't code across. Perform the following steps to capture data:

1. Move your function call from the Update function back to the Start function and reset the translation value to 2.0f. For learning purposes, imagine that your Start function needs to know how far the MoveObject function moved the text to the right. We already know that the movement value is a float, so we can change the return type from void to float. Your function should now look like the one shown in the following code:

2. float MoveObject ()

3. {

4. gameObject.transform.Translate(2.0f, 0.0f, 0.0f);



At this point, the MoveObject function will cause an error because nothing is explicitly returned in the function body. Using a return type in a function necessitates a return, so you'll only want a non-void return type when you're returning valid data every time the function is called. For functions that only offer valid data sometimes, you might consider using a void return type and updating the value of a variable instead.

Now we're faced with two purposes for the translation value instead of just one: we want to apply the value to a translation, and we want to send it back to the caller. If a value is needed more than once, it's a good practice to create a variable. Variables are data that you name and define the type of; they hold a value that can be referred to anytime.

5. Declare and initialize a variable to represent our translation value, as shown in the following code:

6. float MoveObject ()

7. {

8. float translationValue = 2.0f;

9. gameObject.transform.Translate(translationValue, 0.0f, 0.0f);


We declared the variable type first, followed by the name, and then we immediately assigned it a value of 2.0f with the equal to operand. After our variable has a value, we can use it anywhere we would have used 2.0f, such as the X parameter of the Translatefunction.

10. Add a line to return that same value using your variable and satisfy the requirement for a returned float, as shown in the following code:

11.float MoveObject ()


13. float translationValue = 2.0f;

14. gameObject.transform.Translate(translationValue, 0.0f, 0.0f);

15. return translationValue;



Return lines are often the last lines in code blocks because returning a value terminates a function, even if there is code after the return within the same function. You'll get more acquainted with early returns a little later when you're making conditional statements, but always be careful about putting code after a return, because it may never be called.

We can now test the return by reading it in the Start function. For testing purposes, we'll use Unity's print command, a simple way to display data feedback in the bottom-left corner of the development window.

16. Modify your existing function call, as shown in the following code, by instructing it to print out the results:

17.void Start ()


19. print(MoveObject());


We put the MoveObject function call inside the print function call, because we wanted to print whatever the result of the MoveObject function is. Save your changes and press the play arrow button and you'll see the number 2 displayed in the log area at the bottom-left, being read by the print function from the return value.

What just happened?

Often, having a function that simply runs its code and then terminates isn't enough. We need to read values from that function to see what it did, observe changes, and inform other systems about their status. By setting a return value on the function, we let the function talk back to the caller, establishing shared data that can help move a game along quickly.


Putting a return type in a function can sometimes be a double-edged sword; often, returning values is easy and helpful, but since having a return type mandates a return no matter what, you may have to bend more complicated functions to return the data you want, no matter what the circumstances.

Time for action – controlling functions with parameters

Our functions now communicate back to us, but we still haven't communicated to our functions; that's where input parameters come in. Declaring parameters in your function declaration requires the presence of one or many values, without which it couldn't function. For instance, if we wanted our MoveObject function to move the target game object to a different distance each time we called it, we could make that distance one of the required parameters, so each function calling MoveObject will need to tell it how far to translate. Perform the following steps for controlling functions with parameters:

1. Remove the declaration for translationValue on the top line of the MoveObject function and declare a distance parameter, as shown in the following code:

2. float MoveObject ( float translationValue )

3. {

4. gameObject.transform.Translate(translationValue, 0.0f, 0.0f);

5. return translationValue;


We can still refer to the variable translationValue because it's been declared in the parameters instead of the function body, which means the value will come from the function caller instead of the function itself. This also means that we'll have to send the value when the function is called in Start.

6. Input the value of 2.0f into the call. Also, remove the print function call for now, as shown in the following code:

7. void Start ()

8. {

9. MoveObject(2.0f);


Keep in mind that we could also have called this function with a variable, similar to what we did when we declared translationValue inside of MoveObject. We can even pass in a variable declared in Start, as shown in the following code:

void Start ()


float distanceToTranslate = 2.0f;



The name of the variable passed in to the function doesn't have to match the name of the parameter declaration, but the function being called will always access passed data using the parameter name.

You're not limited to one parameter when declaring a function. Functions can carry out many operations at a time on multiple things that are passed in. To demonstrate, we'll add a text parameter to MoveObject, in addition to the distance parameter, and have it print out the value to the log before returning.

10. Add a second parameter of type string and name it textToDisplay. Then, add a line before the return to print its contents to the log. The code is as follows:

11.float MoveObject ( float translationValue,string textToDisplay )


13. gameObject.transform.Translate(translationValue, 0.0f, 0.0f);

14. print(textToDisplay);

15. return translationValue;


16. Now, alter your call to MoveObject in Start so that it provides both required parameters. Note that string values must be contained in quotes.

17.void Start ()


19. float distanceToTranslate = 2.0f;

20. string textToDisplay = "Hello World!"

21. MoveObject(distanceToTranslate, textToDisplay);


Hit the play button after saving your changes and watch the bottom status bar for your string message, which is Hello World!.

What just happened?

Now that you understand return types and function parameters, you can send all sorts of data to and from each function in your script. Single functions make changes, but many functions make games. Learning to establish an exchange of information at every opportunity will let your individual systems shine as a cohesive whole.

Now that you've taken your first steps in scripting, we'll tie everything together by designating a key on the keyboard to call a function that changes the color of your text and returns the current position of the text in the Vector3 format.

Making our scripts interactive

In order for a script to behave based on user input, it needs to be constantly checking for changes in the keyboard state. As this can be considered a perpetual system, we'll use the Update function, which, as you may recall, is called with every frame automatically.

Time for action – adding keyboard interaction to scripts

Perform the following steps to add keyboard interaction to your scripts:

1. Add the following if statement to your Update function that checks if the Return key is pressed:

2. // Update is called once per frame

3. void Update()

4. {

5. if(Input.GetKeyDown(KeyCode.Return))

6. {


8. }


Everything contained within the if statement will run every time the Update function detects that the Return key has just been pressed down (there's a slightly different way to check if a key is being held down, but we'll cover that in the next chapter).

We could add code directly inside the if statement to change the color of the text, but it's better to write a function for an action like that in case you want to replicate the same functionality outside of that if statement without writing redundant code, so we'll create a dedicated ChangeColor function.

9. Declare the ChangeColor function below the Update function in your ColorChanger script, as shown in the following code:

10.void Update()


12. if(Input.GetKeyDown(KeyCode.Return))

13. {


15. }



18.Vector3 ChangeColor(Color newColor)




Note that our new function has a Color parameter so we can pass in any color we want the text to change to, and it has a Vector3 return value so we can retrieve the object's position the moment the function is called.


Typically, a function's return value is related in some way to the operation it performs, which isn't the case with our coloring function returning a position. We're only returning the position as a way to test drive return values; later in the book, we'll incorporate more applicable return values that provide useful information about the status of a function or its end result.

21. Add the following line to your ChangeColor function to assign the passed-in color to the text object:

22.Vector3 ChangeColor(Color newColor)


24. gameObject.renderer.material.color = newColor;


25. Next, add a line that returns the object's current position, as shown in the following code:

26.Vector3 ChangeColor(Color newColor)


28. gameObject.renderer.material.color = newColor;

29. return gameObject.transform.position;


30. Now, your function is ready to be called, so add a call to the if statement you wrote in the Update function that changes the object's color to green:

31.void Update()


33. if(Input.GetkeyDown(KeyCode.Return))

34. {

35. ChangeColor(Color.green);

36. }


37. Press the play button in the Unity editor to test your new function.

The text should still appear red when it begins because you're still setting the color to red in the Start function, but as soon as you press the Return key, the text color will change to green, as shown in the following screenshot:

Time for action – adding keyboard interaction to scripts

Next, we'll add another if statement to check a different key that will change the text to a different color, to demonstrate the dynamic nature of our Color parameter.

38. Add the following if statement to your Update function:

39.void Update()


41. if(Input.GetKeyDown(KeyCode.Return))

42. {

43. ChangeColor(Color.green);

44. }

45. else if(Input.GetKeyDown(KeyCode.Space))

46. {

47. ChangeColor(Color.blue);

48. }


Notice how we began the second if statement with the else keyword. We could have left it as a normal if statement and still achieved the same functionality, but using else if ensures that the second statement is only checked if the first one returns a false result. We'll never have a situation where we need to change the color twice in the same frame, so using else improves the efficiency of our code by handling either one case or the other.

49. Press the play button in the Unity editor and test your prototype to make sure the color of the text changes based on whether the Return key or the Space bar is pressed.

The Return key should still change the text to green, but the Space bar will turn the text to blue, as is shown in the following screenshot:

Time for action – adding keyboard interaction to scripts

You've now created two different behaviors by calling the same function with two different parameters, but we're still not doing anything with the return value. To make sure we're successfully retrieving the position, we'll add a print statement to display it in the information bar at the bottom of the Game window.

50. Add the following print calls to each of your ChangeColor calls, as shown in the following code:

51.void Update()


53. if(Input.GetKeyDown(KeyCode.Return))

54. {

55. print(ChangeColor(Color.green));

56. }

57. else if(Input.GetKeyDown(KeyCode.Space))

58. {

59. print(ChangeColor(Color.blue));

60. }


The print function outputs whatever its parameters provide, which in our case is the return value from the ChangeColor function. Printing the return value is the simplest application of the returned data, but you can use it for anything, including assigning the value to a new variable, as shown in the following code:

Vector3 storedPosition = ChangeColor(Color.green);

61. Press the play button and change the color of the text with either the Return key or the Space bar to observe the printed returned position.

The Vector3 position value will now be printed in the information bar in the bottom-left corner of the Unity editor, as shown in the following screenshot:

Time for action – adding keyboard interaction to scripts

What just happened?

You've taken your first steps in creating interactive code by linking key presses to function calls in your Update function. You made the function dynamic by passing in a color as a parameter instead of explicitly defining it in code, and you returned position data of the calling object using the function's return value.

Input programming gets much more complex than the steps we've reviewed in this tutorial; input can do a lot more than just call a single function, and more complex statements are needed to check input from the OUYA controller instead of just a keyboard. However, before we dive into advanced controller input in the next chapter, we'll deploy what we have to the OUYA to make sure what we have so far is running (even though we can't control it on the OUYA without a keyboard attached to the console).

Deploying our code on OUYA

Now that you have something substantial to show, we'll deploy it to the OUYA and see how the scene carries over to the console.

Time for action – running your first test on OUYA

Perform the following steps to run your code on OUYA:

1. Verify that your project settings are properly configured for deploying to the OUYA.

2. Turn on your OUYA console and connect it to your computer with a USB cable.

3. Verify that your computer recognizes the OUYA console by using the following command in your command line:

adb devices


If your computer isn't able to locate the OUYA console immediately, the solution may be as simple as jump-starting the adb process. Run adb kill-server and then adb devices in your command line to restart the device manager and output a new list of connected devices.

4. Click on Build & Run in Unity's File menu to deploy your prototype to the console. As soon as it's finished building, your 3D text prototype will appear on the screen that your console is connected to.

Remember that you haven't coded any controller-based input yet, so your OUYA controller can't interact with the prototype, but if you connect your keyboard to one of the OUYA's USB ports, you can change the text color just like you could in the Unity editor.


Just because you're programming for a console doesn't mean you can't use keyboard input like you've used in this chapter. Controller support is a must for all OUYA titles, but keyboard and mouse input is supported, and even encouraged, for complex games that native keyboard-and-mouse gamers may feel more comfortable with if they're using their preferred peripherals.

What just happened?

It's not a game yet, but deploying your 3D text prototype to the OUYA console is a good exercise in testing on the device itself; it is an important step in development. The more often you test on the console instead of in the editor, the more often you're experiencing exactly what players will see when they're playing your released product.

Keep in mind that there is no information bar to print values to when running your game on the OUYA. So, for testing that requires a lot of debugging and value reading (or several consecutive tests without spending too much time building and rebuilding), testing in the Unity editor may still be preferential.

Pop quiz – hello world

Q1. What can you use to conveniently store resultant data from a function call?

1. Function parameters

2. A return value

3. A local variable

Q2. What can you use to influence the values that a function interacts with?

1. Function parameters

2. A return value

3. A local variable

Q3. What's the name of the built-in Unity function that gets called with every frame?

1. Start

2. Update

3. MoveObject


You should now have a good understanding of how objects in Unity work. Many objects in your scene share common components such as positions and renderers, but the components of an object, including the scripts you create and attach, are what make it unique.

There is no shortage of pre-built objects, such as lights and cameras, in Unity. Some of these are vital to any game. Stock geometrical objects in Unity, such as planes, cubes, and spheres, are good for establishing basic shapes.

You've also learned all the programming fundamentals you'll need to make a game. It may seem like the code you wrote was small—and there is still plenty to learn—but knowing the anatomy of code as well as how to take advantage of every line and function keyword is the hardest part of programming; the fun lies in transforming your imagination into code.

In the next chapter, you'll continue working with scripts and write code that enables you to interact with the game objects in your scene using your keyboard and OUYA controller. Your knowledge of general input in Unity will form the foundation for all the game mechanics and prototypes you'll make over the course of this book.