Unity Engine: C# Scripting, Physics, and Game Building
Unity is the most widely used game engine in the world, powering over 50% of mobile games and a substantial share of indie and AAA PC titles. Its combination of a powerful editor, C# scripting, extensive asset ecosystem, and cross-platform export makes it the go-to choice for developers ranging from solo indies to studios like Hollow Knight and Heart Machine. This guide covers Unity’s editor interface, C# scripting patterns, physics system, 2D and 3D pipelines, and build workflows, referencing Unity’s official documentation.
Unity Editor Interface
The Unity editor is organized into several dockable panels that provide access to every aspect of project creation.
Scene View and Navigation
The Scene View is the primary workspace for arranging game objects. Navigate using right-click to orbit around the selected object, middle-click or Alt+middle-click to pan, and scroll or Alt+right-click to zoom. The Scene View toolbar provides toggles for 2D mode, lighting, audio, and effects visibility. The grid snapping system (hold Control or Command while moving) snaps objects to grid increments configurable in the Edit menu. Unity’s Scene View documentation provides keyboard shortcuts for all navigation modes and visibility toggles. The Flythrough mode (right-click + WASD) is essential for navigating large 3D scenes.
Game View and Play Mode
The Game View renders from the Main Camera and shows the player experience. The Play button enters Play Mode, where editor changes are temporary: moving an object in Play Mode does not persist when exiting Play Mode. This allows safe experimentation. The Game View aspect ratio dropdown lets you test at different screen resolutions and aspect ratios without leaving the editor. Unity’s Game View documentation covers resolution targets and scale settings for pixel-perfect testing.
Hierarchy, Inspector, and Project Panels
The Hierarchy lists every GameObject in the current scene in parent-child order. Parent transforms apply to children: rotating a parent rotates all children relative to the parent. The Inspector shows all components attached to the selected GameObject: Transform, Renderer, Collider, and custom scripts. The Project panel mirrors your project’s Assets folder and supports search filtering by type (Prefab, Material, Script, Scene). The Unity manual recommends organizing assets into meaningful folder structures: Scripts, Prefabs, Materials, Textures, Scenes, Audio, and UI each get top-level folders.
C# Scripting in Unity
C# is Unity’s primary scripting language, with a comprehensive API covering every engine system.
MonoBehaviour Lifecycle
Every script that needs per-frame updates inherits from MonoBehaviour, which provides lifecycle methods called by the engine. Awake runs when the object is loaded (before Start), suitable for initializing references. Start runs before the first frame update, suitable for game state initialization. Update runs once per frame and is used for most gameplay logic. FixedUpdate runs at a fixed timestep (default 0.02 seconds, 50 Hz) and is the correct place for physics interactions. LateUpdate runs after all Update calls, suitable for camera follow scripts. The Unity Scripting API documentation for MonoBehaviour provides the complete lifecycle diagram with execution order details.
Serialization and the Inspector
Public fields appear in the Inspector by default, allowing designers to tweak values without modifying scripts. The SerializeField attribute exposes private fields to the Inspector while keeping them encapsulated. The Range attribute constrains numeric values to a slider range. The Tooltip attribute provides hover tooltips. For complex data, create custom classes with the System.Serializable attribute to nest data structures in the Inspector. Unity’s Serialization documentation covers the rules for what types can be serialized and common pitfalls with property serialization.
Coroutines and Async Operations
Coroutines pause execution and resume later, useful for timed sequences and asynchronous operations. A coroutine uses IEnumerator return type with yield return statements: yield return new WaitForSeconds(1f) pauses for one second, yield return null waits one frame, yield return new WaitUntil(() => condition) waits until a condition is true. For network operations and asset loading, Unity’s async/await support (using the Awaitable class introduced in 2023.1) provides cleaner syntax than coroutines. The Unity Coroutine documentation includes patterns for chaining coroutines and stopping them safely.
Prefabs and Scene Management
Prefab System
Prefabs are reusable GameObject templates. Create a prefab by dragging a GameObject from the Hierarchy into the Project panel. Instances of the prefab in scenes remain linked: modifying the prefab asset updates all instances. Prefab variants create specialized versions: a BasicEnemy prefab variant adds a new script without affecting the base prefab. Overrides allow per-instance modifications. The Prefab documentation in Unity’s manual details the override workflow and nested prefab support.
Scene Loading and Additive Scenes
LoadScene loads a new scene and unloads the current one. LoadSceneMode.Additive loads a scene on top of the current one, combining content from both. Additive loading is the standard approach for large games: the persistent scene contains managers and UI, and gameplay scenes load additively as the player progresses. SceneManager.LoadSceneAsync provides progress tracking for loading screens. The Unity Scene Management documentation covers build index management, scene loading callbacks, and scene merging.
Physics System
Unity’s physics is built on NVIDIA PhysX for 3D and Box2D for 2D, with dedicated component sets for each dimension.
Rigidbody and Collider Components
The Rigidbody component enables physics: gravity, collision response, and forces. Configure mass (typical range 0.1 to 100), drag (linear air resistance), and angular drag. The isKinematic flag makes the Rigidbody respond to collisions but not forces, useful for moving platforms. Collider components define collision shapes: Box, Sphere, Capsule, Mesh, and Wheel. The isTrigger flag converts the collider to a trigger (detects overlaps without physical collision response). The Unity Physics documentation describes the Rigidbody properties and their gameplay implications in detail.
Physics Queries
Physics.Raycast is the most common physics query: it casts a ray from a point in a direction and returns information about the first object hit. Use LayerMasks to filter which layers the ray interacts with. Physics.OverlapSphere returns all colliders within a spherical radius, useful for area-of-effect damage and proximity detection. Physics.CheckCapsule determines if a capsule volume overlaps any collider, ideal for character height checking. The Unity Physics Query documentation covers performance best practices: reuse RaycastHit structs, use non-allocating overloads, and batch queries where possible.
Character Controller
Unity’s CharacterController component provides a kinematic character with slope limit, step offset, and skin width. It handles collision resolution internally, moving the character and sliding along obstacles. The Move method takes a displacement vector and returns CollisionFlags indicating if the character hit something above, below, or on the sides. The CharacterController is the recommended approach for player characters because it avoids the instability of full rigid body simulation for humanoid movement.
2D Game Development
Unity’s 2D toolset includes dedicated rendering, physics, and level design systems.
Sprite Renderer and Sprite Atlas
The Sprite Renderer displays 2D images with configurable sorting order, color, and material. Sprite Atlases combine multiple sprites into a single texture for draw call batching. The Sprite Atlas asset (Create > Sprite Atlas) packs sprites and generates the atlas at build time. Unity’s 2D documentation recommends using atlases for all projects with more than 10 sprite assets to reduce draw calls.
Tilemap System
The Tilemap system paints 2D levels from a palette of tiles. Create a Tile Palette, populate it with tiles from a tileset, and paint on the Grid game object. The Tilemap Collider 2D automatically generates colliders from tile sprites. The Composite Collider 2D merges adjacent collider tiles into a single shape. Unity’s Tilemap documentation covers rule tiles, animated tiles, and custom brush scripts.
2D Physics
2D physics uses dedicated components: Rigidbody2D, Box Collider 2D, Circle Collider 2D, and Polygon Collider 2D. The physics runs in 2D space with Z-axis rotation. 2D physics materials (Physics Material 2D) control friction and bounce. The Unity 2D Physics documentation covers the component properties and the differences from 3D physics.
3D Game Development
Render Pipelines
Unity offers three render pipelines. The Built-in Render Pipeline is the default, suitable for simple projects but limited in advanced features. The Universal Render Pipeline (URP) balances performance and visual quality with support for 2D and 3D. The High Definition Render Pipeline (HDRP) targets high-end platforms with ray tracing, volumetric lighting, and advanced post-processing. The Unity Render Pipeline documentation helps choose the appropriate pipeline based on target hardware and visual goals.
Lighting and Lightmapping
Unity’s lighting system supports real-time lights (directional, point, spot) and baked lightmaps for static objects. The Progressive Lightmapper bounces light rays to compute indirect lighting, storing results in lightmap textures. Light Probe groups provide indirect lighting information for dynamic objects. Reflection Probes capture the environment for specular reflections on metallic objects. The Unity Lighting documentation covers light contribution sorting and mixed lighting modes.
Building and Publishing
Build Settings and Player Settings
File > Build Settings opens the build configuration window. Add all scenes that should appear in the build to the Scenes In Build list. Player Settings control platform-specific options: company name, product name, icon, splash screen, and rendering settings. The Unity Build Settings documentation covers command-line builds for continuous integration and automated testing pipelines.
Platform-Specific Optimization
For Android, enable the IL2CPP scripting backend for better performance and set Minimum API Level to match your target devices. For iOS, configure the Provisioning Profile and Signing Team ID. For WebGL, reduce texture quality and enable compression. The Unity Platform Optimization pages provide per-platform checklists covering graphics, input, and memory settings.
Asset Bundles and Addressables
Unity Addressables (recommended over legacy Asset Bundles) provide asynchronous asset loading with dependency management and automatic reference counting. Build your Addressables groups, then load assets via Addressables.LoadAssetAsync. This replaces the Resources folder pattern and enables runtime content updates without rebuilding the game.
For engine comparisons, see Unreal Engine Guide and Godot Guide. For 2D-specific workflows, consult 2D Game Development Guide.
Frequently Asked Questions
Q: What is the difference between Update and FixedUpdate? A: Update runs every rendered frame at variable rate. FixedUpdate runs at a fixed timestep (default 50 Hz) regardless of frame rate. Use Update for rendering and input, FixedUpdate for physics and Rigidbody operations. Placing physics in Update causes inconsistent behavior at different frame rates.
Q: How do I optimize a Unity game for mobile? A: Enable the Universal Render Pipeline, reduce texture sizes to 1K or 2K, use texture atlases, limit real-time lights to 1-2, enable GPU instancing, and profile with the Unity Profiler on the target device. Set Quality Settings to the lowest working preset and scale up.
Q: What is the best way to manage scenes in a large Unity project? A: Use additive scene loading with a persistent scene for managers. Organize scenes by level or gameplay section. Use SceneManager.LoadSceneAsync with a loading screen for seamless transitions. Avoid putting all content in a single scene.
Q: Should I use Unity’s built-in physics or a third-party physics asset? A: Use built-in PhysX for most projects. Use third-party assets like Configurable Joint for advanced vehicle physics or custom cloth simulation when built-in options are insufficient. Built-in physics is well-optimized and supported across all Unity platforms.
Q: How do I set up a Unity project for version control? A: Use Unity’s Asset Serialization mode set to Force Text for readable scene and prefab files. Add Library, Temp, and obj to .gitignore. Use UnityYAMLMerge for conflict resolution. Set up a .gitattributes file for LFS tracking on large binary assets.
For a comprehensive overview, read our article on 2D Game Development Guide.
For a comprehensive overview, read our article on 3D Game Development Guide.