You are previewing Unity 5: Learning C# by Developing Games.
O'Reilly logo
Unity 5: Learning C# by Developing Games

Book Description

Explore every nook and cranny of Unity 5 to turn your imaginations into reality

About This Book

  • Demystify the C# programming language in Unity 5.x.

  • Unleash the power of Unity to create a wide variety of projects in numerous genres and formats.

  • Master the art of optimization for Unity 5.x applications with tips and techniques that will further enhance your game.

  • Who This Book Is For

    Beginner level Unity developers who do not have much programming experience.

    What You Will Learn

  • Master the art of applying C# in Unity. Get to know about techniques to turn your game idea into working project.

  • Use loops and collections efficiently in Unity to reduce the amount of code.

  • Create and code a good-looking functional UI system for your game.

  • Find out how to create exciting and interactive games using GUIs.

  • Work with different animation assets and components to enhance your game further.

  • Personalize your game by learning how to use Unity’s advanced animation system.

  • Create, visualize, and edit animated creatures to add to your already amazing game.

  • Familiarize yourself with the tools and practices of game development Discover how to create the Game Manager class to, generate game levels, and develop UI for the game.

  • Use the Unity Profiler to find bottlenecks anywhere in your application, and discover how to resolve them.

  • Implement best practices for C# scripting to avoid common mistakes

  • In Detail

    Unity is a cross-platform game engine that is used to develop 2D and 3D video games. Unity 5 is the latest version, and adds a real-time global illumination to the games; and its powerful new features help to improve a game’s efficiency.

    If you love games and want to learn how to make them but have no idea where to begin, then this course is built just for you. This learning path is divided into three modules which will take you in this incredible journey of creating games.

    The course begins with getting you started with programming behaviors in C# so that you can create 2D games in Unity. You will begin by installing Unity and learning about its features. You will learn how to perform object-oriented programming and discover how to manage the game play loop, generate game levels, and develop a simple UI for the game. By the time this module comes to a close, you will have mastered the art of applying C# in Unity.

    It is now time we put into use what we learned in the previous module into reality as we move onto the second module. Here, we will be building 7-8 action-packed games of different difficulty levels. Each project will focus on key Unity features as well as game strategy development. This module will mark your transformation from an application developer to a full-fledged Unity game developer.

    Who wouldn’t love a game that is fully perfect, functional, and without any glitches? The third module deals with just that by teaching how to enhance your game by learning game optimization skills. Here, you’ll gain an understanding of possible solutions to any problem and how to implement them. You will then learn everything you need to know about where performance bottlenecks can be found, why they happen, and how to work around them.

    With this massive wealth of knowledge, at the end of this learning path, you will be able to leverage an array of game development techniques to create your own basic games while resolving any issues that you encounter.

    Style and approach

    This learning path should be treated as the complete package necessary for building games. It is a step-by-step guide to develop a game from scratch by applying the fundamentals of C# and Unity scripting, with a reference guide in the end to solve all your gaming problems.

    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 code file.

    Table of Contents

    1. Unity 5: Learning C# by Developing Games
      1. Table of Contents
      2. Unity 5: Learning C# by Developing Games
      3. Credits
      4. Preface
        1. What this course covers
        2. What you need for this course
        3. Who this course is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Downloading the color images of this book
          3. Errata
          4. Piracy
          5. Questions
      5. 1. Module 1
        1. 1. Discovering Your Hidden Scripting Skills and Getting Your Environment Ready
          1. Prerequisite knowledge to use this book
          2. Dealing with scriptphobia
          3. Downloading Unity
            1. Obtaining a free license
          4. Teaching behavior to GameObjects
            1. Using Unity's documentation
            2. Do I need to know all that?
          5. C# documentation – where to find it? Do I need it at all?
            1. The Unity community – asking others for help
          6. Working with C# script files
            1. Lots of files can create a mess
            2. Why does my Project tab look different?
          7. Creating a C# script file
          8. Introducing the MonoDevelop code editor
            1. Syncing C# files between MonoDevelop and Unity
            2. Opening LearningScript in MonoDevelop
              1. The namespace – highlighted in blue
              2. The class definition – highlighted in green
            3. Watching for possible gotchas while creating script files in Unity
            4. Fixing synchronization if it isn't working properly
            5. Adding our script to GameObject
          9. Instance? What is it?
          10. Summary
        2. 2. Introducing the Building Blocks for Unity Scripts
          1. Understanding what a variable is and what it does
            1. Naming a variable
            2. A variable name is just a substitute for a value
            3. Creating a variable and seeing how it works
              1. Declaration
              2. Assignment
            4. Click on Play!
            5. Changing variables
            6. Watching for a possible gotcha when using public variables
          2. What is a method?
            1. Using the term "method" instead of "function"
            2. Method names are substitutes, too
          3. Introducing the class
            1. Inheritance
          4. The Start(), Update(), and Awake() methods and the execution order
          5. Components that communicate using dot syntax
            1. What's with the dots?
          6. Making decisions in code
            1. Using the NOT operator to change the condition
            2. Checking many conditions in an if statement
            3. Using else if to make complex decisions
            4. Making decisions based on user input
          7. Paper and pencil are powerful tools

          8. Summary
        3. 3. Getting into the Details of Variables
          1. Writing C# statements properly
          2. Understanding component properties in Unity's Inspector
            1. Variables become component properties
            2. Unity changes script and variable names slightly
          3. Changing a property's value in the Inspector panel
            1. Displaying public variables in the Inspector panel
          4. Private variables
          5. Naming your variables properly
          6. Beginning variable names with lowercase
          7. Using multiword variable names
          8. Declaring a variable and its type
            1. The most common built-in variable types
          9. Assigning values while declaring a variable
          10. Where you declare a variable is important
          11. Variable scope – determining where a variable can be used
          12. Summary
        4. 4. Getting into the Details of Methods
          1. Using methods in a script
          2. Naming methods properly
            1. Beginning method names with an uppercase letter
            2. Using multiword names for a method
            3. Parentheses are part of the method's name
          3. Defining a method the right way
            1. The minimum requirements for defining a method
          4. Understanding parentheses – why are they there?
          5. Specifying a method's parameters
            1. How many parameters can a method have?
          6. Returning a value from a method
            1. Returning the value
              1. Example
          7. Summary
        5. 5. Lists, Arrays, and Dictionaries
          1. What is an array?
            1. Declaring an array
          2. Storing items in the List
            1. Common operations with Lists
          3. List<T> versus arrays
          4. Retrieving the data from the Array or List<T>
            1. Checking the size
          5. ArrayList
          6. Dictionaries
            1. Accessing values
            2. How do I know what's inside my Hashtable?
          7. Summary
        6. 6. Loops
          1. Introduction to loops
          2. The foreach loop
          3. The for loop
            1. An example
          4. The while loop
          5. while versus for loops
          6. Loops in statements
          7. Modulo
          8. Searching for data inside an array
          9. Breaking the loop
          10. Summary
        7. 7. Object, a Container with Variables and Methods
          1. Working with objects is a class act
            1. Few facts
            2. Example
          2. Instantiating an object
          3. Bored yet?
          4. Using methods with objects
          5. Custom constructors
          6. Overloading
          7. Summary
        8. 8. Let's Make a Game! – From Idea to Development
          1. Your first game – avoiding the trap of the never-ending concept
          2. The idea
            1. Game mechanics and core components
          3. Breaking a complex idea into smaller parts
          4. Jake on the mysterious planet – the feature list
            1. Procedural level generation
            2. An animated 2D character
            3. Physics
            4. Mouse and touch controls
            5. Collectables and obstacles
            6. Scoring
            7. UI – the user interface
          5. Target platform and resolution
          6. Target screen resolution
          7. Summary
        9. 9. Starting Your First Game
          1. Setting up a new Unity project for our game
            1. Backup
            2. Keeping your project clean
          2. Preparing the player prefab
            1. Rigidbody2D
            2. CircleCollider2D
          3. PlayerController
          4. User input
            1. Jump
          5. Animator
            1. Running
          6. Code
            1. PlayerController.cs
          7. Summary
        10. 10. Writing GameManager
          1. Gameplay loops
          2. Singleton class
          3. Starting the game
          4. Setting up input keys
          5. Using triggers
          6. Restarting the game
          7. Setting up the player starting position
          8. Code in this chapter
          9. Summary
        11. 11. The Game Level
          1. Generating levels versus designed levels
            1. Creating a level chunk
            2. Planning the LevelGenerator class
            3. Writing LevelGenerator
            4. Commenting on your code
          2. Creating a copy of the level piece
          3. Instantiating
          4. Vector3
          5. Testing LevelGenerator
          6. Extending the level
          7. The code used in this chapter
          8. Summary
        12. 12. The User Interface
          1. Introducting the Unity UI
          2. Views
            1. Constructing the view UI – how to keep things clean
            2. Target screen resolution
            3. Recognizing events
          3. Buttons
            1. A simple button
            2. Image
            3. The Button component
            4. Interaction
            5. The Button action
          4. Hiding and showing the Canvas
          5. Reference exceptions
          6. GameView
            1. Game Over
          7. The code in this chapter
          8. Summary
        13. 13. Collectables — What Next?
          1. Collectables
          2. The coin prefab
            1. The Collectable class
          3. High score and persisting data
          4. The Update function and UI values
          5. What next?
          6. The code in this chapter
          7. Summary
      6. 2. Module 2
        1. 01. 2D Twin-stick Shooter
          1. Project overview
            1. Your objectives
            2. Prerequisites
          2. Setting up the project
          3. Creating our scene
            1. Scripting 101
          4. Implementing player movement
          5. Shooting behavior
          6. Creating enemies
          7. Adding GameController to spawn enemy waves
          8. Particle systems for enemy explosion
          9. Adding in sound effects/music
          10. Adding in points, score, and wave numbers
          11. Publishing the game
          12. Summary
          13. Challenges
        2. 2. Creating GUIs
          1. Project overview
            1. Your objectives
            2. Prerequisites
          2. Creating the main menu level
          3. Adding a header text object
          4. Adding main menu buttons
          5. Pausing the game
          6. Restarting the game
          7. Creating an Options menu
          8. Summary
          9. Challenges
        3. 3. GUIs Part 2 – Clicker Game
          1. Project overview
            1. Your objectives
            2. Prerequisites
          2. Starting our project
          3. Recording and displaying clicks
            1. Working with accessors (get/set functions)
            2. Tooltip and Header attributes
            3. Explaining GameController's functionality
          4. Creating a shop
            1. Making the list scrollable with ScrollView
          5. Opening/closing the shop
          6. Purchasing upgrades
            1. Working with enumerations
            2. Switch statements
            3. Explaining the StoreItem class
            4. Filling in Item descriptions
          7. Summary
          8. Challenges
        4. 4. Mobile Endless Game – Procedural Content
          1. Project overview
            1. Your objectives
          2. Prerequisites
          3. Project setup
          4. Adding the background
          5. Adding a simple animated character
          6. Making a repeating background
            1. Repeating background script
          7. Working with sorting layers
          8. Creating our player behaviour
            1. Stopping the game
          9. Creating obstacles
          10. Spawning obstacles at runtime
          11. Game start and end behaviours
          12. Keeping score
          13. Summary
          14. Challenges
        5. 5. Shooting Gallery – Working with Animations and Tweens
          1. Project overview
            1. Your objectives
          2. Prerequisites
          3. Project setup
          4. Creating the environment
          5. Adding a target
            1. Animating the duck using Unity's animation system
            2. Playing Unity animations via code
            3. Animation using iTween
            4. Creating moving targets
          6. Creating many targets
          7. Creating waves of targets
          8. Adding in a time limit
          9. Adding in Score/High score
            1. PlayerPrefs
              1. Set
              2. Get
          10. Summary
          11. Project completed
          12. Challenges
        6. 6. Side-scrolling Platformer
          1. Project overview
            1. Your objectives
            2. Prerequisites
            3. Project setup
          2. Tile-based level creation
            1. Working with arrays
          3. Creating our player
            1. Adding Jump functionality
            2. Working with Gizmos
            3. Smoothing out player movement
              1. Restricting Jumping
              2. Preventing the player getting stuck
          4. Creating Collectibles
            1. Adding new objects to our level builder
              1. Switch statements continued
          5. Keeping score
            1. Singletons
          6. Winning the game
          7. Summary
          8. Challenges
        7. 7. First Person Shooter Part 1 – Creating Exterior Environments
          1. Project overview
            1. Your objectives
            2. Prerequisites
          2. Project setup
            1. Level design 101 – planning
          3. Introduction to terrain
            1. Height maps
            2. Hand sculpting
          4. Exterior environment – terrain
          5. Adding color to our terrain – textures
            1. Adding multiple textures to a terrain
          6. Adding water
          7. Adding trees
          8. Adding in details – grass
          9. Building atmosphere
          10. Summary
          11. Challenges
        8. 8. First-person Shooter Part 2 – Creating Interior Environments
          1. Project overview
            1. Your objectives
            2. Prerequisites
          2. Project setup
            1. Creating architecture overview
              1. 3D modelling software
              2. Constructing geometry with brushes
              3. Modular tilesets
                1. Mix and match
          3. Importing assets
          4. Creating tiles
          5. Placing tiles with grid snapping
          6. Creating and placing props
          7. Lightmapping quickstart
          8. Summary
          9. Challenges
        9. 9. First Person Shooter Part 3 – Implementing Gameplay and AI
          1. Project overview
            1. Your objectives
          2. Setting up the project
          3. Creating our player
          4. Adding a flashlight
          5. Creating our weapon
            1. Creating our camera
            2. Shooting our camera
          6. Creating an enemy
            1. State machines 101
          7. Enemy movement
            1. Advanced FSMs
          8. Damaging and killing enemies
          9. Using controller input
          10. Moving to other levels
          11. Summary
          12. Challenges
        10. 10. Building an In-Game Level Editor
          1. Project overview
            1. Your objectives
            2. Prerequisites
          2. Level editor – introduction
            1. Lists
          3. Level editor – adding/removing walls at runtime
          4. Level editor – toggling editor, GUI, and selecting additional tiles
            1. The anatomy of a IMGUI control
              1. ControlType
              2. Content
            2. GUI.Button
            3. GUILayout
          5. Level editor – saving/loading levels to file
            1. FileStreams
            2. BinaryFormatter
          6. Summary
          7. Challenges
        11. 11. Finishing Touches
          1. Project overview
            1. Your objectives
            2. Prerequisites
          2. Setting up the build settings
          3. Customizing your exported project via the player settings
          4. Building an installer for Windows
          5. Summary
          6. Challenges
      7. 3. Module 3
        1. 1. Detecting Performance Issues
          1. The Unity Profiler
            1. Launching the Profiler
              1. Editor or standalone instances
              2. Editor profiling
              3. The Unity Webplayer connection
              4. Remote connection to an iOS device
              5. Remote connection to an Android device
            2. The Profiler window
              1. Controls
                1. CPU Area
              2. The GPU Area
              3. The Rendering Area
              4. The Memory Area
              5. The Audio Area
              6. The Physics 3D/2D Area
          2. Best approaches to performance analysis
            1. Verifying script presence
            2. Verifying script count
            3. Minimizing ongoing code changes
            4. Minimizing internal distractions
            5. Minimizing external distractions
          3. Targeted profiling of code segments
            1. Profiler script control
            2. Custom CPU Profiling
          4. Saving and loading Profiler data
            1. Saving Profiler data
            2. Loading Profiler data
          5. Final thoughts on Profiling and Analysis
            1. Understanding the Profiler
            2. Reducing noise
            3. Focusing on the issue
          6. Summary
        2. 2. Scripting Strategies
          1. Cache Component references
          2. Obtaining Components using the fastest method
          3. Removing empty callback declarations
          4. Avoiding the Find() and SendMessage() methods at runtime
            1. Static classes
            2. Singleton Components
            3. Assigning references to pre-existing objects
            4. A global messaging system
              1. A globally accessible object
              2. Registration
              3. Message processing
              4. Implementing the messaging system
              5. Message queuing and processing
              6. Implementing a custom message
              7. Message registration
              8. Message sending
              9. Message cleanup
              10. Wrapping up the messaging system
          5. Disabling unused scripts and objects
            1. Disabling objects by visibility
            2. Disabling objects by distance
          6. Consider using distance-squared over distance
          7. Avoid retrieving string properties from GameObjects
          8. Update, Coroutines, and InvokeRepeating
          9. Consider caching Transform changes
          10. Faster GameObject null reference checks
          11. Summary
        3. 3. The Benefits of Batching
          1. Draw Calls
          2. Materials and Shaders
          3. Dynamic Batching
            1. Vertex attributes
            2. Uniform scaling
            3. Dynamic Batching summary
          4. Static Batching
            1. The Static flag
            2. Memory requirements
            3. Material references
            4. Static Batching caveats
              1. Edit Mode debugging of Static Batching
              2. Avoiding instantiating static meshes at runtime
              3. Visibility and rendering
            5. Static Batching summary
          5. Summary
        4. 4. Kickstart Your Art
          1. Audio
            1. Loading audio files
              1. Profiling audio
              2. Additional loading options
            2. Encoding formats and quality levels
            3. Audio performance enhancements
              1. Minimize active Audio Source count
              2. Minimize Audio Clip references
              3. Enable Force to Mono for 3D sounds
              4. Resample to lower frequencies
              5. Consider all encoding formats
              6. Beware of streaming
              7. Apply Filter effects through Mixer groups to reduce duplication
              8. Use "WWW.audioClip" responsibly
              9. Consider Audio Module files for background music
          2. Texture files
            1. Compression formats
            2. Texture performance enhancements
              1. Reduce Texture file size
              2. Use Mip Maps wisely
              3. Manage resolution downscaling externally
              4. Adjust Anisotropic Filtering levels
              5. Consider Atlasing
              6. Adjust compression rates for non-square Textures
              7. Sparse Textures
              8. Procedural Materials
          3. Mesh and animation files
            1. Reducing polygon count
              1. Tweaking Mesh Compression
              2. Use Read-Write Enabled appropriately
            2. Import/calculate only what's needed
            3. Consider baked animations
            4. Let Unity optimize meshes
            5. Combine meshes
          4. Summary
        5. 5. Faster Physics
          1. Physics Engine internals
            1. Physics and time
              1. The Fixed Update loop
              2. Maximum Allowed Timestep
              3. Physics updates and runtime changes
            2. Static and Dynamic Colliders
            3. Collision detection
            4. Collider types
            5. The Collision Matrix
            6. Rigidbody active and sleeping states
            7. Ray and object casting
          2. Physics performance optimizations
            1. Scene setup
              1. Scaling
              2. Positioning
              3. Mass
            2. Use Static Colliders appropriately
            3. Optimize the Collision Matrix
            4. Prefer discrete collision detection
            5. Modify the FixedUpdate frequency
            6. Adjust the Maximum Allowed Timestep
            7. Minimize cast and bounding-volume checks
            8. Avoid complex Mesh Colliders
              1. Use simpler primitives
              2. Use simpler Mesh Colliders
            9. Avoid complex physics components
            10. Let physics objects sleep
            11. Modify Solver Iteration Count
            12. Optimizing ragdolls
              1. Reduce Joints and Colliders
              2. Avoid inter-ragdoll collisions
              3. Disable or remove inactive ragdolls
            13. Know when to use physics
            14. Consider upgrading to Unity 5
          3. Summary
        6. 6. Dynamic Graphics
          1. Profiling rendering issues
            1. GPU profiling
            2. The Frame Debugger
            3. Brute force testing
            4. CPU-bound
              1. Multithreaded rendering
              2. GPU Skinning
          2. Front end bottlenecks
            1. Level Of Detail
            2. Disable GPU Skinning
            3. Reduce tessellation
          3. Back end bottlenecks
            1. Fill rate
              1. Overdraw
              2. Occlusion Culling
              3. Shader optimization
              4. Consider using Shaders intended for mobile platforms
                1. Use small data types
                2. Avoid changing precision while swizzling
                3. Use GPU-optimized helper functions
                4. Disable unnecessary features
                5. Remove unnecessary input data
                6. Only expose necessary variables
                7. Reduce mathematical complexity
                8. Reduce texture lookups
                9. Avoid conditional statements
                10. Reduce data dependencies
                11. Surface Shaders
                12. Use Shader-based LOD
            2. Memory bandwidth
              1. Use less texture data
              2. Test different GPU Texture Compression formats
              3. Minimize texture sampling
              4. Organize assets to reduce texture swaps
            3. VRAM limits
              1. Texture preloading
              2. Texture thrashing
          4. Lighting and Shadowing
            1. Forward Rendering
            2. Deferred Shading
            3. Vertex Lit Shading (legacy)
            4. Real-time Shadows
            5. Lighting optimization
              1. Use the appropriate Shading Mode
              2. Use Culling Masks
              3. Use Baked Lightmaps
              4. Optimize Shadows
          5. Optimizing graphics for mobile
            1. Minimize Draw Calls
            2. Minimize the Material count
            3. Minimize texture size and Material count
            4. Make textures square and power of 2
            5. Use the lowest possible precision formats in Shaders
            6. Avoid Alpha Testing
          6. Summary
        7. 7. Masterful Memory Management
          1. The Mono platform
            1. The compilation process
              1. Manual JIT compilation
          2. Memory usage optimization
            1. Unity memory domains
              1. Native memory
              2. Managed memory
                1. Garbage collection
                  1. Memory fragmentation
                  2. Garbage collection at runtime
                  3. Threaded garbage collection
                  4. Garbage collection tactics
            2. Value types and Reference types
              1. Pass by value and pass by reference
              2. Structs are Value types
              3. Arrays are Reference types
              4. Strings are immutable Reference types
                1. String concatenation
              5. Boxing
            3. The importance of data layout
            4. The Unity API
            5. The foreach loops
            6. Coroutines
            7. Closures
            8. .NET library functions
            9. Temporary work buffers
            10. Object pooling
          3. Prefab pooling
            1. Poolable Components
            2. The Prefab pooling system
            3. Prefab pools
            4. Object spawning
            5. Instance prespawning
            6. Object despawning
            7. Prefab pool testing
            8. Prefab pooling and Scene loading
            9. Prefab pooling summary
          4. The future of Mono and Unity
          5. Summary
        8. 8. Tactical Tips and Tricks
          1. Editor hotkey tips
            1. GameObjects
            2. Scene View
            3. Arrays
            4. Interface
            5. Other
          2. Editor interface tips
            1. General
            2. The Inspector View
            3. The Project View
            4. The Hierarchy View
            5. The Scene and Game Views
            6. Play Mode
          3. Scripting tips
            1. General
            2. Attributes
              1. Variable attributes
              2. Class attributes
            3. Logging
            4. Useful links
          4. Custom editors/menus tips
          5. External tips
            1. Other tips
          6. Summary
      8. A. Bibliography
      9. Index