Unity Tutorial Part 2: GameObjects

Brian Moakley

Unity-1-feature
Welcome to the second part of this Unity tutorial mini-series! In this part, you’ll learn all about GameObjects in Unity while you give your hero some creepy-crawly aliens to keep him company!

This tutorial continues on from Unity Tutorial Part 1: Getting Started. You can continue on with your completed project from the last chapter, or if you would prefer to start over fresh, you can download the starter project for this tutorial here.

Getting Started

GameObjects represent pretty much all elements in Unity: your player, the aliens, bullets on the screen, the actual level geometry — basically, everything in the game itself.

Just like the Project Browser contains all assets, the Hierarchy contains a list of GameObjects in your scene.

If you don’t have your project open, open it now in Unity.

Note: Unity’s way of opening project files is a bit strange. You can navigate your file system and look for a scene file. Double-click the scene, then Unity will open your project with the current scene selected.

Or, if you start Unity or click File\Open Project, you’ll see a project list. Select the desired project and Unity will take care of the rest.

If your project isn’t listed, click the Open button to bring up a system dialog box. Instead of searching for a particular file, try navigating to the top-level directory of your Unity project and click Select Folder. The engine will detect the Unity project within the folder and open it.

Once your project is open, take a look at your Hierarchy and count the GameObjects.

gameobjects-count

Your first thought may be three because you added three GameObjects in the last chapter: arena, space marine body and space marine head.

However, there are two other GameObjects: Main Camera and Directional Light. Remember how Unity creates these by default? Yes, these are also GameObjects.

Yet, there are even more GameObjects. You’ll notice that there are disclosure triangles to the left of the GameObjects you imported.

Holding down the Alt button on PC or Option on Mac, click each disclosure triangle.

disclosure

As you can see, you have a pile of GameObjects:

lots-of-gameobjects

There’s three important points to remember about GameObjects:

  • GameObjects can contain other GameObjects. On a base level, this useful behavior allows organizing and parenting of GameObjects that are related to each other. More importantly, changes to parent GameObjects may affect their children — more on this in just a moment.
  • Models are converted into GameObjects. Unity creates GameObjects for the various pieces of your model that you can alter like any other GameObject.
  • Everything contained in the Hierarchy is a GameObject. Even things such as cameras and lights are GameObjects. If it’s in the Hierarchy, it’s a GameObject that’s subject to your command.

Our hero is so bored that he’s picking his nose with his gun. You need to get him moving, but first, you need to reposition your GameObjects.

Moving GameObjects

Before starting, collapse all the GameObject trees by clicking the disclosure triangles.

Select BobbleArena in the Hierarchy and take a moment to observe the Inspector, which provides information about the selected GameObject.

GameObjects contain a number of components, which you can think of as small units of functionality. There is one component that all GameObjects contain: the Transform component.

inspector

The Transform component contains the position, rotation, and scale of the GameObject. Using the inspector, you can set these to specific numbers instead of having to rely upon your eyeballs. When hovering the mouse over the axis name, you’ll see arrows appear next to the pointer.

Press the left mouse button and drag the mouse either left or right to adjust those numbers. This trick is an easy way to adjust the values by small increments.

With BobbleArena selected, set Position to (X:-6.624, Y:13.622, Z:6.35). As I developed this game, the arena ended up in this position. You could just as well place it in the center of the game of the game world.

Set the Scale to (X:2.0, Y:2.0, Z:2.0). This gives the player more room to navigate the arena.

arena-setting

If you zoom out of the Scene view, you’ll probably notice the space marine is suspended in the void; mostly likely, he’s questioning his assumptions about gravity. You could move his head and then his body, but your life will be much easier if you group his body parts into one GameObject.

In the Hierarchy, click the Create button and select Create Empty.

create-empty

An empty is a GameObject that has only the one required component of all GameObjects — the Transform component.

Note: You can also create an empty GameObject by clicking GameObject\Create Empty. This goes for other things such as components. There is no “preferred” way to do things — go with whatever works best for your workflow.

Parenting the Space Marine

In the Hierarchy, you’ll see your new GameObject creatively named: GameObject. Single-click the GameObject and name it SpaceMarine.

You can insert spaces in GameObjects’ names, e.g., Space Marine. However, for the sake of consistency, you’ll use camel case for names in this book.

Drag BobbleMarine-Body and BobbleMarine-Head into the SpaceMarine GameObject.

A few things happen when you parent GameObjects. In particular, the position values for the children change even though the GameObjects don’t move. This modification happens because GameObject positions are always relative to the parent GameObject.

parented-objects

Select the SpaceMarine in the Hierarchy. Go to the Scene view and press F to focus on it. Chances are, the arena is blocking your view.

Thankfully, you don’t need to get Dumbledore on speed dial. You can make it disappear yourself! Select BobbleArena in the Hierarchy, and in the Inspector, uncheck the box to the left of the GameObject’s name. This will make the arena disappear.

disable

You only should see the hero now. Select the SpaceMarine GameObject. In the Inspector, mouse over the X position label until you see the scrubber arrows. Hold the left mouse button and move your mouse left or right. Notice how all the GameObjects move relative to the parent.

As you can see, having parents does have its advantages. No offense to any parentless deities out there.

god

When you parent one GameObject in another, the position of the child GameObject won’t change. The difference is the child GameObject is now positioned relative to the parent. That is, setting the child to (0, 0, 0) will move the child to the center of the parent versus the center of the game world.

You’ll do this now to assemble your marine.

Select BobbleMarine-Body, and in the Inspector, set Position to (X:0, Y:0, Z:0). Go select BobbleMarine-Head and set Position to (X:-1.38, Y:6.16, Z:1.05) in the Inspector.

Congratulations! Your hero is assembled.

Positioning the Marine

Now to it’s time to place the space marine in his proper starting position. Select BobbleArena, and in the Inspector, check the box next to the name to reenable it.

Select SpaceMarine, and in the Inspector, set its position to (X:-4.9, Y:12.54, Z:5.87). Also, set the rotation to (X:0, Y:0, Z:0). Your marine should end up directly over the hatch. If this isn’t the case, then feel free to tweak the values until that is the case.

Once the hero is in place, press F in the Scene view so you can see him standing proudly.

final-position

The hero should now be positioned precisely over the elevator, ready to rock. Unfortunately for him, his grandiose rock party will soon degrade into a bug hunt.

Creating Prefabs

This game features creepy crawly bugs, and like the hero, they’re composed of many pieces — some assembly required.

In the Hierarchy, click the Create button and select Create Empty from the drop-down. Single-click the GameObject to name it Alien.

Select Alien in the Hierarchy, and in the Inspector, set the position to: (X:2.9, Y:13.6, Z:8.41).

From the Project Browser, drag BobbleEnemy-Body from the Models folder into the Alien GameObject.

add-body

Set BobbleEnemy-Body Position to(X:0, Y:0, Z:0). Now the alien and hero should be side by side in the arena.

side-by-side

As creepy as the alien is without a head, the hero needs more to shoot at than that spindly little frame. From the Project Browser, drag BobbleEnemy-Head into the Alien GameObject. Set Position to (X:0.26, Y:1.74, Z:0.31), Rotation to (X:-89.96, Y:0, Z:0) and Scale to (X:100, Y:100, Z:100).

alien-head-values

That’s one fierce little bug. They go together so well that you could mistake them for the next superstar crime-fighting duo.

buddy-cop-movie

At this point, you have one parent GameObject for the hero and another for the alien. For the hero, this works great because you need only one. For the alien, you’re going to need many — so, so many.

You could copy and paste the alien to make clones, but they’d all be individuals. If you needed to make a change to the alien’s behavior, you’d have to change each instance.

For this situation, it’s best to use a prefab, which is a master copy that you use to make as many individual copies as you want. Prefabs are your friend because when you change anything about them, you can apply the same to the rest of the instances.

Making a prefab is simple. Select the Alien GameObject and drag it into the Prefabs folder in the Project Browser.

prefab

A few things changed: there’s a new entry in your Prefabs folder with an icon beside it. You’ll also note the name of the GameObject in the Hierarchy is now blue:

new-prefab

Note: You don’t have to drag your model into that specific folder to create a prefab — all that’s required is dragging a GameObject into any folder in the Project Browser. Having a Prefabs folder is simply good housekeeping.

The blue indicates the GameObject has been either instanced from a prefab or a model, such as the BobbleArena. Select the Alien GameObject in the Hierarchy and look at the Inspector; you’ll notice some additional buttons:

prefab-options

Here’s the breakdown of these new buttons:

  • Select will select the prefab inside the Project Browser. This is useful when you have lots of files and want easy access to the prefab to make changes.
  • Revert will undo changes you’ve made to your instance. For example, you might play around with size or color but end up with something horrible, like a viciously pink spider. You’d click the Revert button to restore sanity.
  • Apply will apply any changes you made to that instance to its prefab. All instances of that prefab will be updated as well.

Creating a prefab instance is quite easy. Select the Alien prefab in the Project Browser and drag it next to your other Alien in the Scene view.

make-a-prefab

You can also drag an instance to the Hierarchy. As you can see, creating more aliens is as easy as dragging the Alien prefab from the Project Browser. But you don’t need droves of aliens yet, so delete all the Aliens from the Hierarchy. You delete a GameObject by selecting it in the Hierarchy, and pressing Delete on your keyboard, (Command–Delete on a Mac), or you can right-click it and select Delete.

Fixing the Models

The next to-do is fixing some of your models. In this case, Unity imported your models but lost references to the textures.

In the Models folder of your Project Browser, drag a BobbleArena-Column into the Scene view. You’ll find a dull white material.

textureless-column

If a material name or texture name changes in the source package, Unity will lose connection to that material. It tries to fix this by creating a new material for you that has no textures attached to it.

To fix this, you have to assign a new texture to the material. In the Project Browser, select the Models subfolder and then, expand the BobbleArena-Column to see all the child objects.

fix-model1

Next, select Cube_001 in the Project Browser, and in the Inspector, click the disclosure triangle for the Main_Material shader.

fix-model2

You’ll see that there are a lot of options! These options configure how this material will look.

materials

For example, the Metallic slider determines the metal-like quality of the material. A high value metallic value means the texture will reflect light much like metal. You’ll notice a grey box to the left of most of the properties. These boxes are meant for textures.

In this case, all you want is a an image on your model. In the Project Browser, select the Textures folder. Click and drag the Bobble Wars Marine texture to the Albedo property box located in the shader properties.

fix-model3

The Albedo property is for textures, but you can put colors there are well. Once you do this, your columns will now have a texture.

textured-column

The arena also suffered a texture mishap. In the Hierarchy, expand the BobbleArena and then expand Floor. Select the Floor Piece.

floor-piece

In the Inspector, you’ll notice two materials attached to the floor piece. The BobbleArena-Main_Texture material does not have a texture assigned to it. You can tell because the material preview is all white.

material-preview

Like you did for the column, select the Textures folder in the Project Browser. Click and drag the Bobble Wars Marine texture to the Albedo property box located in the shader properties.

Your floor will now acquire borders. How stylish!

floor

You’ll also notice that not just one, but all floor sections acquired borders. This is because they all use the same material.

Adding Obstacles

Now, that you have your models fixed, it’s time add a bunch of columns to the arena. You’ll make a total of seven columns, and you’ll use prefabs for this task.

Note: Whenever it seems like you should make a duplicate of a GameObject, use a prefab instead — it’s another best practice. Some Unity developers insist on using prefabs for everything, even unique objects.

The thinking is that it’s much easier to create a prefab and make duplicates than it is to turn a group of existing GameObjects into prefab instance. The former method requires minimal work whereas the latter requires you to extract the commonalities into a prefab while maintaining any unique changes for each instance. This results in a lot of work.

In the Hierarchy, drag the BobbleArena-Column into your Prefabs folder to turn it into a prefab. With BobbleArena-Column instance still selected in the Hierarchy View, go to the Inspector and set position to (X:1.66, Y:12.83, Z:-54.48). Set scale to (X:3.5, Y:3.5, Z:3.5). You do want all the prefabs to be the same scale, so click the Apply button.

column-position

Now it’s time for you to make the rest of the columns. Dragging one column at a time from project to project in the Scene view can be a little tedious, especially when there are several instances. Duplicate a column by selecting one in the Hierarchy and pressing Ctrl–D on PC or Command–D on Mac.

Create a total of six duplicates and give them following positions:

  • Column 1: (X:-44.69, Y:12.83, Z:-28.25)
  • Column 2: (X:42.10, Y:12.83, Z:30.14)
  • Column 3: (X:-8.29, Y:12.83, Z:63.04)
  • Column 4: (X:80.40, Y:12.83, Z:-13.65)
  • Column 5: (X:-91.79, Y:12.83, Z:-13.65)
  • Column 6: (X:-48.69, Y:12.83, Z:33.74)

You should now have seven columns in the arena.

column-position4

The arena looks good, but the Hierarchy is a bit messy. Tidy it up by clicking the Create button and select Create Empty. Rename the GameObject to Columns and drag each column into it.

total-columns

You’ll notice the columns have a similar name with unique numbers appended to them. Since they essentially act as one entity, it’s fine for them to share a name. Hold the Shift key and select all the columns in the Hierarchy. In the Inspector, change the name to Column.

change-name

Note: As you can see, it’s possible to change a common property for a bunch of GameObjects at once.

Creating Spawn Points

What good are bloodthirsty aliens unless they spawn in mass quantities? In this section, you’ll set up spawn points to produce enemies to keep our hero on his toes.

So far, you’ve assembled the game with GameObjects that you want the player to see. When it comes to spawn points, you don’t want anybody to see them. Yet, it’s important that you know where they are.

You could create a 3D cube and place it in your scene to represent a spawn point, then remove it when the game starts, but that’s a clunky approach.

Thankfully, Unity provides a simpler mechanism called labels. These are GameObjects that are visible in the Scene view, but invisible during gameplay.

To see them in action, you’ll create a bunch of different spawn points similar to how you created the columns.

Click the Create button in the Hierarchy and select Create Empty. Give it the name Spawn and set position to (X:-5.44, Y:13.69, Z:90.30).

In the Inspector, click the colored cube next to the checkmark. A flyout with all the different label styles will appear. Click blue capsule.

label-styles

Look at your Scene view; you’ll see it’s been annotated with the Spawn point.

spawn-point

You need to create ten more spawn points. Make placement easier by doing the following:

  1. In the Scene view, click on the center cube of the scene gizmo to switch the Scene view to Isometric mode.
  2. Click the green y-axis arrow so that you look down on the scene.

gizmo

Now duplicate and reposition ten more spawn points, according to the following image:

spawn-points

Don’t worry if you don’t get them exactly the same — game design is more of an art than a science!

Once you’re done, click the Create button in the Hierarchy, select Create Empty and name it SpawnPoints. Drag all the spawn points into it. Batch rename them like you did with the columns to Spawn.

spawn

Congratulations! Your game is now properly set up. Make sure to save!

Where to Go From Here?

You can download the completed project for this tutorial here.

At this point, you have your hero, his enemy the alien, and the arena in which they will battle to the death. You’ve even created spawn points for the little buggers. As you set things up, you learned about the following:

  • GameObjects and why they are so important when working with Unity.
  • Prefabs for when you want to create many instances of a single GameObject.
  • Labels to help you annotate game development without interfering with the game.

In the next section of this tutorial mini-series, you’ll add some action to this game, learn how to work with Components and let your space marine fire away at will!

If you’re enjoying this tutorial series and want to learn more, you should definitely check out Unity Games by Tutorials.

The book teaches you everything you need to know about building games in Unity, whether you’re a beginner or a more experienced game developer. In the book, you’ll build four great games:

  • A 3D twin-stick shooter
  • A classic 2D platformer
  • A 3D tower-defense game (with virtual reality mode!)
  • A first-person shooter

The book is still in development, but here’s a preview of the first game you’ll build in the book:

If you have questions or comments on this tutorial, please leave them in the discussion below!

Brian Moakley

Brian leads the Unity team at raywenderlich.com and also produces video tutorials on iOS, Unity, and various other topics.

Brian joins Razeware with experience from companies such as ESPN’s online fantasy team and Disney’s Internet Group. When not writing or coding, Brian enjoys story driven first person shooters, reading some great books, and he runs his own "Let's Play" channel on YouTube (vzombie.lol).

Other Items of Interest

Save time.
Learn more with our video courses.

raywenderlich.com Weekly

Sign up to receive the latest tutorials from raywenderlich.com each week, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

PragmaConf 2016 Come check out Alt U

Our Books

Our Team

Video Team

... 20 total!

Swift Team

... 15 total!

iOS Team

... 28 total!

Android Team

... 15 total!

macOS Team

... 10 total!

Apple Game Frameworks Team

... 11 total!

Unity Team

... 11 total!

Articles Team

... 11 total!

Resident Authors Team

... 15 total!