C# VARIABLES, DATA TYPES & SCOPE IN UNITY

A programmer's guide to storing game data: primitive types, structs, reference handles, inspector attributes, and why [SerializeField] private is superior to public variables.

1. The 6 Most Common Data Types in Unity

float (Single Precision)
Stores decimal numbers (e.g. float speed = 12.5f;). Always append the f suffix. Used for speed, health, time, and percentages.
int (32-bit Integer)
Stores whole numbers without decimals (e.g. int ammoCount = 30;). Used for inventory counts, player level, score, and kill counts.
bool (Boolean)
Stores either true or false (e.g. bool isGrounded = true;). Used for state flags, toggles, and conditions.
Vector3 (3D Coordinates)
Contains (x, y, z) float components (e.g. Vector3 offset = new Vector3(0, 2, -5);). Used for position, velocity, and force.

2. Why [SerializeField] private is Industry Standard

Beginner tutorials often declare variables as public float speed = 10f; solely to expose them in the Unity Inspector. However, making variables public creates architectural vulnerability:

  • Any other script in your game can accidentally mutate player.speed = -999f; without validation.
  • It tightly couples scripts and makes refactoring painful.

The Solution: Use [SerializeField] private to expose variables to the Inspector while keeping them safely encapsulated:

using UnityEngine;

public class AircraftStats : MonoBehaviour
{
    [Header("Flight Parameters")]
    [Tooltip("Maximum forward airspeed in knots.")]
    [Range(50f, 600f)]
    [SerializeField] private float maxSpeed = 350f;

    [Tooltip("Rate of climb in meters per second.")]
    [SerializeField] private float climbRate = 25f;

    // Public read-only property provides safe external access
    public float MaxSpeed => maxSpeed;
    public float ClimbRate => climbRate;
}

3. Power Inspector Attributes

  • [Header("Section Title")]: Creates a clean bold category header in the Inspector.
  • [Tooltip("Help text")]: Displays helpful hover tooltips when hovering over the variable.
  • [Range(min, max)]: Replaces the numeric input field with a safe slider to prevent out-of-bounds input.
  • [Space(10)]: Adds vertical padding between fields.

Related C# Guides & Tools

Frequently Asked Questions

Once a serialized variable is attached to a GameObject in a scene or prefab, Unity saves the serialized value in the YAML scene file. If you later change float speed = 10f; to float speed = 25f; in code, Unity retains the serialized 10f saved in the scene. To update it, right click the script component in the Inspector and click Reset.
Variable shadowing occurs when a method parameter or local variable shares the exact same name as a class field (e.g. float speed inside a method shadowing class field this.speed). The local variable hides the class field within that block, leading to subtle bugs where the class field never gets updated.