Charpter 2 of Developing 2D Game
Chapter 2
Introduction to Unity
This chapter covers the Unity Editior -- installing, configuring, navigating its windows, using its toolset, and getting familiar with the project structure. Not all of this material will be immediately relevant to your everyday work in Unity, and you'll probably have to refer back to this chapter a few times in the future anyway, so don't try to commit it all to memory on the first go.
Install Unity
First thing's first: head over to https://store.unity.com and download Unity. Because we're just learning to use Unity, get the Personal version, which is free.
For our purpose in this book, the main difference between the free version and the plus tier is that the free version flashes the "Made with Unity" on the splash screen, which the Plus verion allows you to create a custom splash screen. The Plus, Pro, and Enterprise versions get gradually more expensive, but offer interesting benifits such as better analytics and control over your data, multiplayer features, test builds using the Unity Cloud service, and even access to the source code at the Enterprise level.
You should remember that these tiers your qualification for each tier is determined by revenue. If you or your game comany generate less than $100k/year USD, you qualify to use Unity Personal Edition free of charge. If your company generates less than $200k/year USD, you're required to use the Unity Plus tier. Finally, if your company generates more than $200k/year USD you must use Unity Pro. Not a bade deal at all.
While installing Unity, the Unity Download Assistant will prompt you to select which compoents o fthe Unity Editor you want to install. Ensure that the following components are checked off: Unity 2018 ( or the most recent version ), Documentation, Standard Assets, and Example project. We'll be building our sample game to run stand-alone on your desktop( PC, Mac, or Linux ) in this book. If you'd like, you can also check off boxes to install the components for WebGL, iOS, or Android Build Support to build for those platforms as well.
Configure Unity
After installing Unity and running for the first time, you'll be prompted to sign in to your account. Creating and signing into an account isn't readly necessary unless you want to take advantage of some more advanced features such as Cloud Builds and Ads, but there's no harm in creating an account and signing in anyway. You'll need an account if you want to use anything from the Unity Asset Store.
Let's go through Unity's Projects and Learning screen, as seen in figure 2-2, and point out a few things. On the upper left, you'll notice two tabs Projects and Learn.
On Disk
A history of the last six projects you've worked on will apprear, and can be opened by selecting them.
In the cloud
This refers to using cloud-based collaborative projects, which we won't be covering. Unity Teams has a feature called Unity Collaborate that allows team mebers to update files in ta project and publish those changes to tthe cloud. Other team members can then view those changes and decide whether to sync their local project with the cahgnes or ignore them. If you've ever worked with Git, Unity Collaborates is very similar, but whereas Git has a bit of a learning cureve, Unity Collaborate is intentionally designed to be very visuall and eay to use.
Now select the Learn tab.
The Learn section has a wealthe of information and you could easily spend a few weeks going through all the tutorials, sample projects, resources, and links. Don't be afraid to open up sample projects that look well beyound the scopre of what you alreaxdy konw. Poke around, tweek things and break things. That's how learing happens. If you break something and can't fix it, you can alwayss close and relead the sample project.
Ok, let's start creating our project.
Select "New" from the top right of the Projects and Learnig Screen.
You'll be presented with a screen, seen in Fighure 2-3, containing a few configuration options for setting up your new project.
The default name of a new Unity project is, "New Unity Project.". Change the Project Name to be "RPG" or "Greatest RPG Ever", as seen in Figure 2-3. Select the radio button next to 2D to configure the project to show a side view in 2D at all times. Don't worry if you forget to set this--it's easy to switch once our project is created.
Note the file path in the Location text box. That's where Untiy will save your project. I like to organize source code on my computer inside a parent directory called "source" with Unity code inside a "Unity" subdirectory, but you can organize your directory structure however you wish. If you're logged in, you'll see a toggle switch to turn on Unity Analytics. You can leave this setting turned off, as we won't be using it.
The Script Editor: Visual Studio
As of Unity 2018.1, Visual studio is now the default script editor for developing C# scripts. Historically, the built-in script editor shipped with Unity was MonoDevelop, but starting with Unity 2018.1, Unity ships with Visual Studio for Mac instead of MonoDevelop on macOS. On Windows, Unity ships with Visual Studio 2017 Community and no longer ships with MonoDevelop.
Next up, we'll get to know the Unity Editor.
Navigating the Unity interface
Stretching across the top of the Unity Editor is the tool bar, which consists of the Transform Toolset, Tool Handle controls, the Play, Pause, and stop Controls, the Cloud Collaboration. Selector, Serives, button, Account Selector, Layer Selector, and Layout Selector. We'll go throught all of the these at the appropriate time.
The Unity interface is made up of a number of window views, which we'll review next.
Understanding the different Window views
Let's go through the various views displayerd in the default Editor Layout. There are many views available other than those we discuss below, and we'll cover some of them later in this book.
. Scene View
Scenes can be thought of as the foudation of Unity Projects, so you'll have the Scene View open most of the time while you're working in the Unity Editor. Everything that happens in your game takes place in a Scene. The Scene View is where we'll construct our game and od most of our work with sprites and colliders. Scenes contain GameObjects and they hold all the functionality relevant to that Scene. We'll cover GameObjects in more detail in Chapter 3, but for now just know that every object in a Unity Scene is a GameObject.
. Game View
The Game View renders yoiur game from the currently active camera's point of view. The Game View is also where you'll view and play your actual game while you're working on it in Untidy Editor. There are ways of building and running your game outside of Unity Editor as well, such as a stand-alone application, in a Web browser, or on a mobile phone, and we'll cover some of these platforms later in this book.
. Asset Store
A compeling factor when choosing Unity to build games is the Unity Asset Store. As discussed in Chapter 1, the Unity Asset Store is an online storefront where artists, developers, and content creators can upload conent to be bought and sold. The Unity Editor has a built-in tab that connects to the Asset Store for convenience, but you can also access the Asset Store via the Web at https://assetstore.unity.com. Although there's no harm in having this pane available in your Layout, there's also no harm in hiding it and only opening it when you need something from the Asset Store.
. hierarchy Window
The Hierarchy Window displays a list of all objects in the current Scene in a hierarchical format. The Hierarchy Window also allows for the creation of new GameObjects via the "Create" drop-down menu in the top-left corner. The search field allows a developer to serach for specific GameObjects by name.
In Unity, GameObjects can contain other GameObjects in what's called a "parent-child" relationship. The Hierarchy Window will display thess relationshipos in a helpful nested format. Figure 2-5 portrays the Hierarchy Window view in an example Scene.
Here's a brief explanation about what we mean by "parent-child" relationships in the Hierarchy Window. The example Scene in figure 2-5 is called GameScene, ant it contains a GameObject called Environment. Environment is a parent object to several GameObjects, including one called Ground. Ground is a child object with respect to Environment. However, Ground contains several child objects of its own, including Tree, Bush, and Roads. Ground is the parent object with respect to these child objects.
. Project Window
the Project Window gives an overview of all the content is the Assets foler. it's helpful to create folders in the Project Window to organize items such as audio files, materials, models, textures, scenes, and scripts. Throughout the lifetime of your project, you'll spend a lot of time dragging and rearranging assets in folders and selecting those assets to view them in the inspector Window. In this book, we'll demonstratoe a suggested project folder stucture, but you should fell free to rearrange things in a way that makes logical sense to you and the way you like to work.
. Console View
The console view will display errors, warnings, and other output from your Unity application. There are C# scripting functions that can be used to ouput information to the Console View at runtime to aid in debugging. We'll cover those later on when we discuss debuging. You can toggle the varous forms of output on and off via the three buttons in the top-right of the console view.
Tip Somehitngs you'll get an error message that occurs with every Unity frame update, and those messages will clog up your Console View in a hurry. In situations like this, it's helpful to hit the Collapse toggle button to collapse alll indentical error messages into a single message.
. Inspector Window
The Inspector Window is one of the most useful and important windows in the Unity Editor; be user to familiarize yourslef with it. Scenes in Unity are made up of GameObjects, whihc consist of Components such as Scripts, Meshes, Colliders, and other elements. You can select a GameObjecta and use the Inspector to view and edit the attached Components and their respective properties. There are even techniqures to create your own properties on GameObjects that can then be modified. We'll cover this more in later chapters. Cameras, Materials, and Assets as well. If an Asset is selected, such as an audio file, the Inspector will show details such as how the file was loaded, its imported isze, and the compression ratio. Assets such as Materal Maps will allow you to inspect the Rendering Mode and Shader.
Tip Notice that you can access many of the more commonly used panes via the shortcut: Control(PC) or Cmd/(Mac) + number. for example, control 1, and control 2 to swith bewteen the scene view and Game View, respectivaly on Mac. This is a good way to save some time and avoid having to use the mouse for more common pane swithcing.
Configure and Customize the layout
Each pane can be rearraged by grabbing the tab on the top-left of the pane and dragging it. Unity allows a use to create a custom Editor layout by dragging around panes, locking them into place, resizing them to your liking, and then saving that layout.
To save the layout, you have two options:
. Go to the menu option: Window->layouts->save Layout. When prompted, give your custom layout a name, and hit the Save button.
. Click the layout selector in the top-right-most corner of the Unity editor (figure 2-6 ). It will say Default at first. Then select Save Layout and give your custom layout a name and hit the save button.
You can load any layout int the feature from the same menu: Window->layouts, or use the layout selector. If you want to reset your layout, simply select Default from the layout selector.
The Transform Toolset
Next, we'll go through the different buttons and toggles that make up the toolbar. The three things to note with the tool bar for now are: the transform toolset; the tool handle Controls; and the Play, Pause, and Step Controls. There are other controls on the tool bar but we'll get ot those then we start to use them.
The Transform tools (figure 2-7) allow a user to navigate around the Scene view and interact with GameObjects.
The six Transform tools, from left to right, are:
. Hand
The hand tool allows you to left-click and drage the mouse around the screen to pan around the view. Note that you won't be able to select any objects when the Hand tool is selected.
. Move
Selecting the Move tool and selecting a GameObject in either the Hierarchy or Scene View will allow you to move that object around the screen.
. Rotate
The Rotate tool ratates selected objects.
. Scale
The Scale tool scales selected objects.
. Rect
The Rect tool allows for the moving and resizing of selected objects using 2D Handles, which will appear on the selected object.
. Move, Rotate, or Scale Selected Objectes
This tool is a combination of the Move, Rotate, and Scale tools, consolidated into one set ot handles.
At any time, you can temporarily switch to the Hand tool ( only in 2D projects ) by pressing Option( Mac ) or Alt(PC) and move around the scene.
Tip The six controls in the Transform toolset are individually mapped to the following six keys: Q, W, E, R, T, Y. Use thes hot-keys to qulickly switch between tools.
A useful trick when using the Move tool ( hot-key: W ) is to have the GameObject snap to specific increments by holding down control(PC ) or Cmd /(Mac). Adjust the snap increment settings in Edit->Snap Settings menu.
Handle Position Controls
To the right of the transform toolset you'll find the handle postion controls, as see in figure 2-8.
Handles are the GUI controls on objects used to manipulate them in a Scene. The handle position controls allow you to adjust the position of the Handles for selected objects and how they are oriented.
The first toggle button ( see figure 2-8) allows you to set the postion of the handles.
The tow options for postion are:
. Pivot: this places the Handles at the selected object's pivot point.
. Center: this places the Handles at the center of the selected object.
The second toggle button allows you to set the orientation of the Handles. Note that the orientation button will be grayed out if the Scale tool is selected, as orientation doestn't pertain to scale. the two orientation options are:
. Local: when selected, a Transform tools functionality will be relative to the GameObject.
. Global: when selected, a Transform tools functionallity will be relative to the world space orientation.
Tip It's possible to change the pivot point of a Sprite by Selectiong the sprite in the project window, swithcing the sprite mode to multiple in the Inspector, and clicking the sprite editor button. Tap the Slice button in the Spirte Editor and select a Pivot point from the drop-down menu.
Play, Pause, and Stop controls
The unity editor has two modes: play mode and edit mode. When the play button is pressed, provided there are no bugs preventing the game from building, the Unity editor enters Play Mode and switches to the Game View( see figure 2-9 ). The shortcut to enter play mode is control(PC ) or Cmd/ (Mac) + P.
While still in play Mode, you can swith back to Scene View by selecting the tab at the top of the Scene Pance if you want to inspect GameObjects int eh running Scene. This is helpful if you need to debug a scene. While in Play Mode, you also can press the Pause button at any time to pause the running Scene. The shortcut to pause the scene is Control+Shift+p on PC, and Cmd/(Mac ) +shift +P on Mac.
The Step button allows Untify to advance a single frame, and then pause, and then pause again. This is helpful for debugging as well. The shortcut to Stop ahead by a singel frame is Control + Alt +P on PC, and Cmd/(Mac ) + Option + P on Mac.
Pressting the Pla button again while in Play Mode will stop playing the Scene, switch the Unity Editor back to Edit Mode, and switch back to Scene View.
an important thing to always remember when working in Play Mode is that any changes you make to objects will NOT be saved or relfected in the Scene once the Editor switches back to Edit mode. It's very easy to forget about this while a scene is running, amke some changes and tweak things until they're prefect, only to have those changes lost when you stop playing.
Tip to make it super obvious that you're in Play Mode, its' useful to configure Untiy preferences to switch the background tint color of the editor automatically when entering Play Mode. To do so, go to the menu option as seen in Figure 2-10:Untiy->Preferences. Select Colors from the options on the left, and look for the section header, "General.". Select your perfered bacground tint color and exit out. Now hit the Play button to see the results. The background of the Untiy Editor should be tinted to your selected color.
Unity Project Structure
The main two Unity project folers to know are the Assets/foler and the projectSettins/ folder. If you're using any form fo source version control, these are the two folders you should check in.
The Assets/ folder is wher all game resources are located including scripts, images, sound files and so forth.
The ProjectSettings/ folder, as the name suggests, contains all types of project settings pertaining to physics, audio, networking, tags, time, meshes, and so on. Everything set from the menu Edit->Projects Settings is stroed in this foler.
There are other folers and files in the Unity project structre but they're all generated based off of the contents of Assets/ or ProjectSettings/. The Library/ folder is a local acche for imported assets, and Temp/ is used for temporray files generated during the build process. Files ending with a .csproj extension are C# project files, and files ending with .sln are solution fiels used for the visual Studio IDE.
Unity Docutmentation
Unity is very well documented, and the ducumentation available on Unity's website(https://docs.unity3d.com/) covers the scripting API as well as working the Unity Editor. Unity also has dozens of video turorials with content appropriate for all levels of developer expericence in the Learn portal( https://unity3d.com/learn). The unity forums (https://forum.unity.com/ )are the place for discussions about Unity topics, and Unity Ansers(https://answers.unity.com) is a great resource to post questions and get help from fellow Unity developers in the community.
Summary
We've covered a lot of material in this chapter that will be relevant to your futre as a Unity Game Developer. We introduced the most commonly used windows in the Untiy Editor such as Scene View, where you construct your game, and Game View, where you can view your game running. We discussed how the Hierarchy Window gives an overview of all GameObjects in the current scene, how to edit the properties of these GameObjects in the Inspector, and how to manipulate them via the Transform Toolset, and Handle Position controls. Along the way, we discussed how to change the layout of these windows and views and save that layout for future use. We learned how the console view will display error messages and can be used for debugging when issues arise with our game. We concluded the chapter by poiniting out the extensive Unity documentation, video tutorials, discussion forums, and Q&A resources.