The Ultimate Beginners Guide To Game Development In Unity

Hugo Dolan
Mar 21, 2019 · 13 min read

Unity is a great tool for prototyping everything from games, to interactive visualisations. In this article, we run through all you need to know to get started using Unity.

First, a little bit about me: I’m a hobbyist unity developer, 3d modeler and graphic designer who’s worked with Unity and Blender for over 5 years. I’m now a Financial Maths student at University College Dublin, and occasionally I do freelance graphic design, web prototyping, and game prototyping.

Image for post
Image for post
Concept art is one of the earliest phases in the game dev process, over the last 5 years i’ve got a lot of exposure to all areas of game design. Check out my Portfolio of Graphic, UX, Concept Art, Game Dev etc…

Introduction

Why Unity?

If you want to make games

Unity is probably the least opinionated of the 3 platforms. It gives you a very raw product out of the box, but is highly flexible, well-documented, and highly extensible to build pretty much any genre of game you can think of.

There are plenty of highly successful games such as Escape from Tarkov (FPS), Monument Valley (Puzzler), and This War of Mine (Strategy / Survival) all built in Unity.

In reality the engine you build your first game on is probably not critical, so my advice is just to pick one and go with it.

If you want to prototype user experiences

Unity has full support for VR and AR and hence could be a great tool for exploring architecture, automations and simulations with clients.

Sections to this article

  • Unity Editor Window
  • Unity Game Objects
  • Unity Builtin Components
  • Creating Custom Components
  • Structure of a MonoBehaviour
  • Manipulating GameObjects
  • Raycasting
  • Collision detection
  • Advanced Features
  • Advice For Newcomers
  • Nice Resources and Communities
  • Conclusion

Unity editor window

Image for post
Image for post

Scene View: Allows placement and movement of GameObjects in the Scene

Game View: Previews how the player will see the scene from the camera

Inspector: Provide details on the selected GameObject in the scene.

Assets / Project: All prefabs, textures, models, scripts etc are stored here

Hierarchy: Enables nesting and structuring of GameObjects within the scene

Now we’re good to start!

Unity Game Objects

What are GameObjects

Anything you place within a scene in Unity must be wrapped in a ‘game object.’

If you’ve got a web design background, you can think of GameObjects as being a lot like <div> elements! Extremely boring containers, but are highly extensible to create complex functionality or visuals.

Image for post
Image for post
I’ve lifted this straight out of the Unity editor window just to make this point.

Literally everything from particle effects, cameras, players, UI elements, … (the list goes on) is a GameObject.

Creating Hierarchy

The logic behind nesting game objects is much the same as web development, I’ll give a few examples…

Clutter & Efficiency

Web Analogy: You’ve got many similar elements which may be dynamically generated on the fly in response to user interaction and want to keep them tidy.

Unity Translation: Your building a Minecraft clone and you’ve loads of blocks in the scene, you need to add and remove ‘chunks’ of blocks from the scene for performance reasons. Thus having them parented to an empty GameObject for each chunk makes sense, as deleting the chunk parent removes all the children blocks.

Positioning

Web Analogy: You want to keep the position of the content contained ‘relative’ to the container and not to the web page.

Unity Translation: You’ve created a bunch of helper drones which hover around the player. You would really not rather write code to tell them to chase after the player, so instead you instantiate them as children of the player game object.

Unity Builtin Components

The Actor Component Model

Unity works off an Actor Component model, put simply the GameObjects are the actors and the Components are your scripts.

If you’ve written any web apps before you’ll be familiar with the idea of creating small reusable components such as buttons, form elements, flexible layouts that have various different directives and customisable properties. Then assembling these small components into larger web pages.

The big advantage of this approach is the level of reusability and clearly defined communication channels between elements. Likewise in game development, we want to minimise the risk of unintended side effects. Small bugs tend to spiral out of control if you’re not careful, and are extremely difficult to debug. Thus creating small, robust and reusable components is critical.

Key Built-in Components

  • MeshFilter: Allows you to assign materials to a 3D mesh to a GameObject
  • MeshRender: Allows you to assign materials to a 3D Mesh
  • [Box | Mesh]Collider: Enables detection of GameObject during collisions
  • Rigidbody: Enables realistic physic simulation to act on GameObjects with 3d Meshes and will be trigger detection events on box colliders
  • Light: Illuminates portions of your scene
  • Camera: Defines the player viewport to be attached to a GameObject
  • Various UI Canvas Components for displaying GUIs

There are loads more, but these are the main ones you’ll need to get familiar with. One tip is that you can access all the docs for these through the unity manual and scripting reference offline wherever you are:

Image for post
Image for post
Just click on the help section, the docs in general are pretty good

Creating Custom Components

To start creating components, go into the desired GameObject > Add Component > type the name of your new component in the search bar > new script (c#).

As a general recommendation I’d advise against using Javascript in Unity. It hasn’t been kept updated with all the great stuff that came with ES6, and most of the more advanced stuff relies on C# stuff ported over to Javascript… It just becomes a one giant work-around in my experience.

Structure of a MonoBehaviour

Key Functions

  • void Start() which is called whenever an object containing the script is instantiated in the scene. This is useful anytime we want to perform some initialisation code, eg. set a player’s equipment after they spawn into a match.
  • void Update() which is called every frame. This is where the bulk of code involving user input will go, updating various properties such as the motion of the player in the scene.

Inspector Variables

Another example where we might want to do this is when creating a UI component that tracks user mouse movements and places a cursor in the viewport. Here we might want to control the sensitivity of the cursor to movements (if the user was using a joystick or gamepad vs a computer mouse). Thus it would make sense to have these variable easy to change both in edit mode and also experiment with them during runtime.

Image for post
Image for post
Variables in the inspector window can be changed at any time during runtime or edit mode. Note: Changes made during runtime will not be permanent.

We can do this easily by simply declaring them as public variables in the body of the component.

Image for post
Image for post
Notice how we can make variables have different levels of access, private, public, or public but not displayed in the inspector window.

Accepting user input

  • Input.GetKey(KeyCode.W) Returns True W key is being held down
  • Input.GetKeyDown(KeyCode.W) Returns True when W key is first pressed
  • Input.GetAxis(“Vertical”), Input.GetAxis(“Horizontal”) Returns between -1,1 mouse input movement

Manipulating GameObjects

  • Translation, Rotation, Scale
  • Create new GameObjects
  • Sending messages to existing GameObjects / components

Transformations

Image for post
Image for post

The methods above are fairly self explanatory, just note that we use lowercase gameObject to refer to the GameObject which owns this specific instance of the component.

In general it’s a good practice to use local[Position,Rotation] rather than the global position / rotation of an object. This usually makes it easier to move objects in a manner that makes sense, as the local space axis will be oriented and centered on the parent object rather than the world origin and x,y,z directions.

Image for post
Image for post
The benefits of local space become a little more obvious with a diagram!

If you need to convert between local and world space (which often is the case) you can use the following:

Image for post
Image for post

As you can imagine, there is some fairly simple linear algebra behind this hinted at by the ‘Inverse’ in the method name.

Creating new GameObjects

First we need to introduce the notion of a Prefab. We can create these simply by dragging any GameObject in the scene hierarchy into the assets folder.

Image for post
Image for post
What prefab looks like in the Asset tab

This essentially stores a template of the object we just had in our scene with all the same configurations.

Image for post
Image for post
An example of a custom brick object which is used to dynamically generate Lego bricks in a scene, it has a bunch of components attached to it with various default values.

Once we have these prefab components we can assign them to inspector variables (as we talked about earlier) on any component in the scene, so that we can create new GameObjects as specified by the prefab at any time.

We can then perform ‘instantiation’ of the prefab and manipulate it to the desired location in the scene and establish the necessary parent relationships.

Image for post
Image for post

Accessing other GameObjects and Components

ComponentName comp = some_game_object.GetComponent<ComponentName>();

After that you can access any of the public methods / variables of the component in order to manipulate the GameObject. This is the straightforward bit, however actually obtaining the reference to the GameObject can be done in several ways…

Access via inspector variable

Access via tagging

Image for post
Image for post

This is simply done as below.

GameObject some_game_object = GameObject.FindGameObjectWithTag(“Brick”);

Access via transform

ComponentName comp = gameObject.transform.parent.GetComponent<ComponentName>();

Access via SendMessage

gameObject.SendMessage(“MethodName”,params); // Broadcast message

gameObject.SendMessageUpwards(“MethodName”, params); // Only received by components which are nested above.

Raycasting

There are two scenarios where this comes in handy (There’s probably loads more):

  1. If you were designing a weapon system for a game, you could use raycasting for hit detection, and even customise the length of the ray so that melee items ‘hit’ only at short ranges
  2. Create a ray from the mouse pointer to a point in 3d space, ie if you wish the user to be able to select units with their mouse in a strategy game.
Image for post
Image for post
Example 2 detailed above

As you can see, the code for this is a little bit more involved. The key thing to understand is that to cast a ray to where the mouse is pointing in 3d space requires the ScreenPointToRay transformation. The reason for this is the camera is rendering a 3d space as a 2d viewport on your laptop screen, so naturally there is a projection involved to transfer back to 3d.

Collision detection

Once setup within any custom component attached to the object, we can use the OnCollisionEnter, OnCollisionStay and OnCollisionExit methods to respond to collisions. Once we have the collision information we can get the GameObject responsible and use what we learned earlier to interact with components attached to it as well.

Image for post
Image for post

One thing to note is that rigid-bodies provide physics such as gravity for objects, so if you want this turned off you will need to check the is_kinematic on.

Image for post
Image for post
Check on is kinematic to disable unwanted physics but retain nice collision detection.

Advanced Features

Creating GUI’s

Extending the Unity Editor

Animation

Materials and PBR

Advice For Newcomers

Pick a simple concept and break it down into small achievable milestones. It’s highly recommended to separate your game into as small independent components as possible, as you’re much less likely to run into bugs if you keep the components simple rather than monolithic code blocks.

Before you go and write any code for any part of your game, go and research what someone else has done before to solve the same problem — chances are they’ll have a much slicker solution.

Nice Resources and Communities

Concept Art

3D Modelling

  • CG Cookie (Best Mesh Modeling Basics in Blender Ever, they’ve loads of other excellent content for blender)
  • Tor Frick (Hard Surface Modelers & Sculptors in Blender)
  • Gleb Alexandrov (Short powerful rendering tutorials in Blender)

Game Design

Programming

Conclusion

Image for post
Image for post

Don’t forget to clap for this tutorial if you liked it and follow me here on Medium if you want to see more in the future!

freeCodeCamp.org

This is no longer updated.

Hugo Dolan

Written by

UCD Statistics & ACM, Learning Data Science, Winning Team @ Citadel Dublin Data Open. www.hugodolan.com/linkedin | Mailing List: http://eepurl.com/gkV7ov

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Hugo Dolan

Written by

UCD Statistics & ACM, Learning Data Science, Winning Team @ Citadel Dublin Data Open. www.hugodolan.com/linkedin | Mailing List: http://eepurl.com/gkV7ov

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store