O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Unity 2017 Game Development Essentials - Third Edition

Book Description

Go through 3D game development techniques using Unity

About This Book

  • Kick-start your game development carrer and build ready-to-play 2D and 3D games with ease
  • Understand the key concepts in game design including scripting, physics, instantiation, particle effects, and more
  • Build games that run on desktop, mobile, and the web

Who This Book Is For

Who this book is written for: If you're a designer or animator who wishes to take their first steps into game development or prototyping, or if you've simply spent many hours sitting in front of video games with ideas bubbling away in the back of your mind, Unity and this book should be your starting point.

What You Will Learn

  • Script games using C#
  • Build your very first 2D and 3D games
  • Work through the key concepts in game development such as animations, physics, and scripting
  • Test and optimize your games to attain great performance
  • Create fully functional menus, HUDs, and UI
  • Create player character interactions with AI and NPC

In Detail

Unity is the most popular game engine among Indie developers, start-ups, and medium to large independent game development companies. This book is a complete exercise in game development covering environments, physics, sound, particles, and much more—to get you up and running with Unity rapidly.

In this informal guide, you'll get to grips with the basics of game development, starting off with using C# for scripting. You'll get the hang of Unity's development environment and will be able to set up the required assets for your frst 2D game. You'll work on animating your player and getting it to move in the 2D environment. Next, you'll see how to build the game in 3D, making use of Unity's new 3D animation system. After building a beautiful 3D environment for the game, you'll work with the latest physics system that Unity has to offer and will make your assets interactive. You'll induce artifcial intelligence into the enemies and develop a mechanism to hit them with rocks and punches. Once you've made things pretty with the particle system, you'll move on to optimize the game, adding a cross-platform ready UI, and publishing your game across multiple platforms.

You'll walk away with a cool 2D parallax side parallax game and an even cooler third-person 3D adventure game, but most importantly, with the confdence to build your own games.

Style and approach

This book provides a set of easy-to-follow examples, culminating in the production of a first person 2D and 3D game. It builds a solid foundation in game development concepts through an example-driven approach and takes you to the point where you can confidently leverage all the features of Unity to build multi-platforms games of all genres.

Downloading the example code for this book 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.

Table of Contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  2. Entering the Third Dimension
    1. Getting to grips with 3D
      1. Coordinates
      2. Local space versus world space
      3. Vectors
      4. Cameras
        1. Projection mode – 3D versus 2D
    2. Polygons, edges, vertices, and meshes
    3. Shaders, materials, and textures
    4. Rigidbody physics
      1. Collision detection
    5. Softbody physics
      1. The Cloth component
    6. Getting to grips with 2D in 3D
      1. Ignoring one axis
      2. Understanding Sprites
    7. Essential Unity concepts
      1. The Unity way – an example
      2. Assets
      3. Scenes
      4. GameObjects
      5. Components
      6. Scripts
      7. Prefabs
    8. The interface
      1. The Scene view and Hierarchy view
      2. Control tools
        1. Scene navigation
        2. Control bar
        3. Create button
      3. The Inspector
      4. The Project window
      5. The Game view
    9. Summary
  3. Prototyping and Scripting Basics
    1. Your first Unity project
      1. A basic prototyping environment
      2. Setting the scene
      3. Adding simple lighting
      4. Another brick in the wall
        1. Building the master brick
          1. Creating our first prefab
        2. And snap! It's a row
        3. Grouping and duplicating with empty objects
          1. Build it up, knock it down!
    2. Introducing C# scripting
      1. A new behavior script or class
      2. What's inside a new C# Monobehaviour class
        1. Base Monobehaviour methods
        2. Variables in C#
        3. Comments
    3. Write the Shooter class
      1. Declaring public variables
      2. Assigning scripts to objects
      3. Moving the camera
      4. Local, private, and public variables
      5. Understanding Translate
      6. Implementing Translate
        1. Testing the game so far
      7. Making a projectile
        1. Creating the projectile prefab
        2. Creating and applying a material
        3. Adding physics with a Rigidbody
    4. Saving prefabs
      1. Firing the projectile
        1. Using Instantiate() to spawn objects
        2. Adding a force to the Rigidbody
          1. Resetting the wall to initial state and clearing the projectiles
    5. Summary
  4. Creating and Setting Game Assets
    1. Setting up the scene and preparing game assets
      1. Placing the prefabs in the game
        1. Importing and placing background layers
    2. Implementing parallax scrolling
      1. Making it last forever
        1. Using the Asset Store
        2. The FreeParallax component
        3. Understanding and setting up elements
        4. Playing in the middleground
          1. Avoiding holes and discrepancies on the ground collider
          2. Putting in the foreground and special layers
        5. Creating a death zone
      2. Spawning collectable items
    3. 2D animation basics
      1. Importing animated Sprites
      2. The Animator component
      3. Animator state-machine editor
        1. Transitions between animation states
        2. Conditions and parameters
      4. Final words
    4. Summary
  5. Player Controller and Further Scripting
    1. Working with the Inspector
      1. Tags
      2. Layers
      3. Prefabs and the Inspector
    2. Scripting with Unity
      1. Statements
      2. Variables
        1. Variable data types
        2. Using variables
        3. Public and private variables
        4. Declaring  variables
    3. Full code example
      1. Functions
        1. Update()
        2. OnMouseDown()
      2. Writing custom functions
        1. Return type
        2. Arguments
      3. Declaring a custom function
        1. Calling a custom function
      4. If else statements
      5. Multiple conditions
        1. For loops
    4. Inter-script communication and Dot Syntax
      1. Accessing other objects
      2. Find() and FindWithTag()
      3. SendMessage
      4. GetComponent
        1. Programming for mobile
        2. Dot Syntax
      5. Null reference exceptions
      6. Coroutines
      7. Comments
        1. Further reading
    5. Anatomy of a 2D character
      1. Extending the Platformer2DUserControl class
        1. Making the player and writing the game logic
        2. Analyzing, understanding, and modifying the component's source code
        3. Defining a namespace
      2. Spawning collectible items
      3. Adding a timer
      4. Making things difficult with health and obstacles
        1. Layer Collision Matrix
      5. Making it look and sound better
        1. Adding a simple shadow for the character
        2. Inserting audio: environmental sfx, background music, sound events
        3. Sprite shading with real-time lights
      6. Writing some additional game logic
      7. Homework
    6. Summary
  6. Character Animation with Unity
    1. Unity Legacy Animation System
      1. Importing character models and animations
      2. Importing animations using multiple model files
      3. Setting up the animation
    2. Building the Player with Animator
      1. What is an avatar in Unity?
      2. Configuring an avatar
        1. Fixing issues with the default bone mapping
        2. Configuring muscle actions and settings
      3. Importing animation clips for Animator
        1. Setting up animations to ensure correct looping
      4. Scaling the model
    3. Understanding Animator
      1. Animator component
        1. Animator component properties
      2. Animator controller
        1. The Animator window
      3. Animator state machine
        1. Understanding the state machine
        2. Controlling a character's behavior with state machines
      4. Animation states
        1. What's the Any State state?
        2. Our first Blend Tree state
        3. Conclusions
      5. Controlling Animator through code with parameters
    4. Root-motion animations
      1. Using a better approach – Root motion
      2. Animation transitions
        1. Setting the transitions between states
      3. Blend Trees
        1. Modifying Unity standard assets classes to implement our playing character
      4. Adding the final touches
        1. Cloth simulation – giving life to hero's hair and skirt
        2. Inverse Kinematics
    5. Summary
  7. Creating the Environment
    1. Designing the game
    2. Understanding and using the Terrain tool
      1. Setting terrain features
        1. Setting the terrain size detail and resolution
        2. Importing and exporting 2D heightmaps
      2. The terrain tool
        1. Terrain component
        2. Raise height
        3. Paint Height
        4. Flatten Heightmap
        5. Smooth Height
        6. Paint Texture
        7. Place Trees
        8. Refresh (tree prototypes)
        9. Edit Trees
        10. Mass placement of trees
        11. Paint details
        12. Refresh (detail prototypes)
        13. Edit details
        14. Terrain Settings
    3. Creating the island
      1. Step 1 – Setting up the terrain
      2. Step 2 – Creating the island outline
      3. Step 3 – A small lake carving
      4. Step 4 – Adding textures
        1. Painting procedure
        2. Sandy areas
        3. Adding grass and rock
      5. Step 5 – Tree time
      6. Step 6: The grass is always greener
      7. Step 7 – Let there be light!
        1. Creating sunlight
        2. Procedural skybox
      8. Step 8 – Surrounding the island with sea water
        1. A small lake
      9. Step 9: What's that sound?
        1. Positional audio versus non-positional audio
        2. Audio file formats
        3. The hills are alive!
        4. Importing the book's asset package
        5. Further audio settings
        6. Enabling positional 3D sound and setting up curves
      10. Step 10 – Walkabout
      11. Step 11: Final tweaks
    4. Summary
  8. Interactions, Collisions, and Pathfinding
    1. Digital content creation applications
      1. Common import settings for models
        1. Model
        2. Materials
      2. Animation
        1. Wrap Mode
        2. Animation Compression
    2. Setting up the hut model
      1. Adding the model
      2. Positioning the model
      3. Manually adding the colliders
      4. Physic Material
      5. Adding audio
    3. Collisions and triggers overview
      1. Ray casting
        1. Predictive collision detection
    4. Opening the old man's hut door
      1. Approach 1 – collision detection
        1. Creating new assets
        2. Character collision detection
          1. Working with OnCollisionEnter
        3. Writing the OpenDoor() method
        4. Declaring the function
        5. Checking the door status
        6. Playing an audio event
        7. Testing the script
        8. Extending colliders
        9. Playing door animations through Animator
        10. Reversing the procedure
        11. Code maintainability
        12. Drawbacks of collision detection
      2. Approach 2 – ray casting
        1. Disabling collision detection with comments
        2. Refactoring the code – writing a Door Manager class
        3. Tidying PlayerCollisions
        4. Casting the ray
        5. Resetting the collider
      3. Approach 3 – trigger collision detection
        1. Creating and scaling the trigger zone
        2. Scripting for trigger collisions
          1. Removing the PlayerCollisions component
      4. Placing additional models
    5. Unity Navigation System
      1. The Bake tab
      2. The Agents tab
      3. The Object tab
      4. The Areas tab
        1. Area Types and Navigation cost
        2. Area mask
    6. Summary
  9. AI, NPC, and Further Scripting
    1. Creating an NPC
      1. Initial code and Animator Controller
      2. Animator transitions
      3. Navigation setup
        1. Baking the NavMesh
        2. Adding the rock stone and NPCsitSpot and NPCStartSpot points
      4. Writing the Simple AI class
      5. NPC interaction
        1. Triggering the dialogue
      6. Writing the DialogueManager class
        1. Tying up the logic and UI events
        2. Driving Animator Blend Tree with scripting
      7. Creating a basic UI for displaying the dialogue
        1. Creating the Canvas
        2. Creating the start dialogue prompt
        3. Creating the dialogue window
          1. Creating the answer buttons
    2. Making enemy AI
      1. Using Unity Standard Assets in our favor
      2. Making the AI smarter
        1. Duplicate ThirdPersonCharacter class
        2. Creating the Advanced AI Controller class
        3. Custom AI state machine
        4. Waypoints roaming
        5. Chasing the target
        6. Back to waypoints roaming
        7. Enemy's Field Of View (or line of sight)
        8. Player presence awareness
        9. Fighting the player
        10. Modifying the chase method
        11. Debugging the Nav Mesh Agent
      3. A better look for our custom components with PropertyDrawers
      4. Further lectures and ideas
        1. Tips for enhancing the AI
    3. Summary
  10. Item Collection, Player Inventory, and HUD
    1. Creating the ancient artifact piece prefabs
      1. Downloading, importing, and placing
      2. Tagging the artifact piece
      3. Collider scaling and rotation
        1. Enlarging the artifact piece
        2. Adding a trigger collider
        3. Collider scale and custom point light
      4. Creating the artifact piece collection script
        1. Making it spin
      5. Adding trigger collision detection
      6. Saving as a prefab
    2. Placing the artifact pieces
    3. Player inventory
      1. Saving the artifact collected piece count value
        1. Setting the variable start value
        2. Audio feedback
      2. Adding the PiecePickup() method
        1. Adding the inventory to the player
      3. Restricting hidden piece spot access
        1. Restricting dialog access with a piece counter
    4. Displaying the game progression status HUD
      1. Import settings for UI images
      2. Creating the HUD panel and background UI image
      3. Scripting for UI image activation
        1. Understanding arrays
      4. Adding QuestIndicator images
      5. Draw order of elements
      6. Disabling the HUD for game start
      7. Enabling the HUD
    5. Hints for the player
      1. Writing on screen with UI Text
      2. Scripting for UI Text control
      3. Adjusting hints to show progress
    6. Summary
  11. Instantiation and Rigidbodies
    1. Implementing instantiation
      1. Physics
        1. Forces
        2. The Rigidbody component
    2. Designing the gameplay
      1. Creating the heavy stone prefab
        1. Adding physics to the stone prefab
        2. Saving as a prefab
    3. Throwing stones at guards
      1. The StoneLauncher component
      2. Checking for player input
      3. Writing the Fight method
      4. Instantiating the heavy stone
      5. Naming instances
      6. Assigning velocity
      7. Adding development safeguards
        1. Checking component presence
        2. Safeguarding collisions
          1. Using the IgnoreCollision() method
          2. Ignoring collisions with layers
      8. Final tweaks
      9. Instantiation restriction and object tidying
      10. Implementing  stone throw animation
        1. Activating the stone launch at the right frame
      11. Removing stones in a smart way
    4. Finishing touches
      1. Ragdoll physics simulation
        1. Scripting the ragdoll simulation
    5. Reviving the enemy
      1. Using coroutines to time game elements
      2. Collision detection
      3. Punching the guards
        1. Playing stones collisions feedback sounds
        2. Adding force impulse to stones impacts
    6. Summary
  12. Unity Particle System
    1. What is a Particle System?
    2. Creating the fireplace
    3. Creating wall torches
      1. Modifying the Fire Light component
    4. Enhancing environment ambience
      1. Making the village ground dusty
    5. Creating a sea breeze particle system
      1. The Gradient Editor
    6. Creating a waterfall
    7. Summary
  13. Designing Menus with Unity UI
    1. Unity UI
      1. Canvas render modes
        1. Screen space – overlay
        2. Screen space – camera
        3. World space
      2. Preparing textures for UI usage
    2. Creating the main menu scene
      1. Adding the game title
        1. Manually anchoring the title to the Canvas
      2. Creating the main menu panel
        1. Adding buttons
        2. Clone the MainMenu to obtain the Options menu
        3. Configuring UI buttons to show/hide menus with the OnClick() event method
      3. Creating an audio options menu
        1. Adding music volume control
        2. Adding general volume control
        3. Writing a listener script for UI slider elements
        4. User interaction
      4. Creating a video options menu
        1. The power of UI dynamic variables and UI events
        2. Creating a drop-down menu
        3. Yet another slider controller
        4. Loading the game
    3. Final touches
      1. Lights and shadows
        1. Adding a Rim light
        2. Real-time shadows
      2. Post-processing image effects
        1. FSAA (Full Screen Anti-Aliasing)
        2. Bloom and HDR
        3. Screen overlay
        4. Vignette and chromatic aberration
      3. Splitting the render on two different cameras
        1. Adding jail bars to the scene
    4. Conclusion
      1. Testing screen sizes
      2. Further looks
    5. Summary
  14. Optimization and Final Touches
    1. Tweaking the terrain
      1. Using SpeedTree
      2. Hills, troughs, rocks, and texture blending
        1. Smoothing and painting
        2. Keep on the right path by drawing path details with splat maps
        3. Some level design: placing the guards
    2. Unity lighting
      1. Scene setup
        1. The Enviroment settings
        2. Realtime lighting and Mixed Lighting
          1. Realtime only versus Baked only versus Mixed lighting
        3. Lightmaps and baked Global Illumination
      2. Baking the scene
        1. Preparing for lighting
        2. Including or excluding lights from the baking
        3. Excluding GameObjects from the bake
      3. Baking the scene
        1. Lightmapping Settings
      4. Global maps
      5. Object maps
        1. Other settings
    3. Optimizing performance
      1. Camera clip planes (frustum culling)
        1. Standard fog versus Global Fog post effect
      2. Occlusion culling
        1. The Object tab
        2. The Bake tab
        3. The Visualization tab
    4. Wrapping it all up
      1. Rendering paths
        1. Graphics pipelines
        2. Forward Rendering
        3. Deferred Rendering
          1. Lighting performance
          2. Should I use Deferred?
      2. Physical-Based Rendering:  Unity Standard Shader
      3. Image effects
        1. Hardware-based anti-aliasing (MSAA) versus shader-based anti-aliasing(FSAA)
        2. Depth of field
          1. Debugging depth of field
        3. Crepuscular sun rays through Sun Shafts effect
      4. The Post Processing Stack
        1. Post Processing Stack V2 and Utilities
          1. Focus puller
    5. Advanced rendering features
      1. Level of Detail (LOD)
      2. High Dynamic Range
      3. Asynchronous Texture Upload
      4. Graphic Command buffers
    6. Unity Engine automated optimizations
      1. Static and dynamic batching
        1. Static batching
        2. Dynamic batching
        3. GPU instancing
      2. Cull and cull more!
        1. Camera culling distance
          1. Modifying the FireLight class
    7. Further optimizations
      1. Physics optimizations
        1. Writing the DeactivateRagdollTimer class
        2. Changing the HeavyStone class
        3. Exercise proposal: a rough save game-status feature
      2. Optimizing AI impact on the CPU
        1. Setting up AI Trigger areas
        2. Other ideas
    8. Summary
  15. Building and Sharing
    1. Supported platforms
      1. PC (Windows), Linux, or Mac standalone
      2. Android platform
      3. iOS
      4. WebGL
      5. Virtual, augmented, and mixed reality
    2. Player settings
      1. Cross-platform general settings
      2. Per-platform player settings
      3. Mac - PC - Linux - standalone build
        1. Resolution and Presentation
          1. User input bindings
        2. Icon
        3. Splash image
          1. Splash screen
          2. Logos
          3. Background
        4. Other settings
          1. Rendering
          2. Configuration and optimization
          3. Logging
        5. XR settings
      4. Android
      5. iOS
      6. WebGL
    3. Player input settings
    4. Graphics settings
      1. Tier settings
    5. Quality settings
      1. Quality settings - Rendering
      2. Quality settings - Shadows
      3. Quality settings – Other
    6. Building the game
      1. Build settings
        1. Quit button with platform automation
      2. Our first build
        1. Building the standalone for PC/Mac/Linux
    7. Adapting for the web
      1. Building for the web
    8. Adapting and building for the mobile platform
      1. Adapting for Android
        1. Texture Compression formats
      2. Building for Android
        1. Choosing the preferred build system
        2. Publishing settings
      3. Building for iOS
    9. Testing and debugging
      1. Debugging with Visual Studio 2017
      2. Testing and profiling with Unity Editor
        1. Unity Profiler
        2. The Physics Debug window
        3. The Frame Debug window
    10. Sharing your work
      1. Sharing WebGL builds
      2. Publishing on mobile stores
      3. Publishing for the desktop
      4. Digital Content Creation tools
      5. Future of Unity and MonoBehaviour
      6. Testing and further study
      7. Learn by doing
    11. Testing and finalizing
      1. Public alpha testing and open beta
      2. Frame rate feedback
        1. Testing different video resolutions
      3. Optimizing more
    12. Approaches to learning
      1. Don't reinvent the wheel
      2. Editor extensions
      3. Complete projects
      4. If you don't know how to do it, just ask!
    13. Summary
  16. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think