Courses

C# for Unity Beginners: The Scripting Basics You Need

The C# you actually need for your first Unity games: variables, methods, Start and Update, components, collisions and prefabs, explained with one small game.

By Nazmul Hussain Published Updated 7 min read

A laptop showing a C# script in a code editor beside the Unity editor with a simple 2D coin-collecting game

Most people who open Unity for the first time can build a scene in an afternoon: drag in a sprite, add a floor, press Play. Then nothing moves, because movement, scoring and every rule of your game live in code. This guide covers C# for Unity beginners: the small set of scripting ideas that power almost every early game, explained with one tiny coin-collecting game you can build this week. It is the same foundation we teach in month one of Omebly Academy’s Game Development course.

Quick answer: To script in Unity you need about ten C# ideas: variables and types, if statements, methods, classes, the MonoBehaviour lifecycle (Awake, Start, Update, FixedUpdate), the Inspector, GetComponent, Time.deltaTime, collision and trigger events, and Instantiate and Destroy with prefabs. Learn them by building small games, not by reading C# theory for weeks first.

How C# fits into Unity

In Unity, a game is made of GameObjects (a player, a coin, a camera) and each GameObject is a bundle of components (a Transform for position, a SpriteRenderer for the picture, a Rigidbody2D for physics). A C# script is simply another component that you write yourself.

That one idea explains a lot:

  • A script does nothing until it is attached to a GameObject in a scene.
  • The script talks to the other components on the same object to move it, change its colour or play a sound.
  • The same script can be attached to many objects. Fifty coins can share one Coin script.

Every script you create from the Unity editor starts like this:

using UnityEngine;

public class Coin : MonoBehaviour
{
    void Start()
    {
    }

    void Update()
    {
    }
}

MonoBehaviour is the Unity class that turns your C# class into a component. The class name must match the file name exactly (Coin.cs holds class Coin), or Unity won’t let you attach it.

The C# basics you will use every day

Variables and types

A variable stores a value your game needs to remember. C# makes you say what kind of value it is.

Type Holds Game example
int Whole numbers Score, lives, ammo
float Decimals (write 5f) Speed, jump force, timer
bool true or false isGrounded, isPaused
string Text Player name, a message
Vector2 / Vector3 A position or direction Spawn point, velocity
GameObject A reference to an object The enemy prefab to spawn
Rigidbody2D, Transform A reference to a component The physics body to move

If statements, loops and methods

  • If statements make decisions: if lives reach zero, show the game-over screen.
  • Loops repeat work: for (int i = 0; i < 5; i++) spawns five enemies.
  • Methods group steps under a name, such as TakeDamage(int amount), so you can call them from anywhere.

Classes and access

A class is a blueprint; each attached script is an instance of it. Fields marked private are hidden from other scripts, which keeps your code tidy. Add [SerializeField] to a private field to make it appear in the Inspector, so you can tweak speed or health without touching code:

[SerializeField] private float speed = 5f;

Many tutorials use public fields instead. That works, but it lets every other script change the value. [SerializeField] private is the better habit.

If you want more plain C# practice outside Unity, Microsoft’s C# documentation has free beginner tutorials you can run in the browser.

The Unity lifecycle: when your code runs

Unity calls certain methods for you at set moments. You never call Update() yourself; you just write it, and Unity runs it every frame.

Method When it runs Use it for
Awake() Once, when the object loads Grabbing references with GetComponent
Start() Once, before the first frame Setting starting values
Update() Every frame Reading input, timers, simple logic
FixedUpdate() On the physics timestep Moving Rigidbodies, applying forces
LateUpdate() After all Updates Camera follow
OnDestroy() When the object is removed Cleanup

Unity’s manual has the full event function execution order if you want the complete picture.

Time.deltaTime

A fast PC runs more frames per second than a budget phone. If you move an object by 0.1 every frame, it moves faster on the fast PC. Multiply by Time.deltaTime (the seconds since the last frame) so movement is measured per second instead:

transform.Translate(Vector3.right * speed * Time.deltaTime);

Build it: a tiny coin collector in three scripts

Set up a 2D scene with a player sprite, a floor and a few coin sprites. Give the player a Rigidbody2D and a BoxCollider2D, tag it “Player”, and give each coin a CircleCollider2D with Is Trigger ticked.

Script 1: player movement

Recent Unity 6 projects use the Input System package for keyboard input, so this example uses it:

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMove : MonoBehaviour
{
    [SerializeField] private float speed = 5f;
    private Rigidbody2D rb;
    private float moveX;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        moveX = 0f;
        if (Keyboard.current.leftArrowKey.isPressed) moveX = -1f;
        if (Keyboard.current.rightArrowKey.isPressed) moveX = 1f;
    }

    void FixedUpdate()
    {
        rb.linearVelocity = new Vector2(moveX * speed, rb.linearVelocity.y);
    }
}

Notice the split: input is read in Update, physics happens in FixedUpdate. In Unity versions before 6, linearVelocity is called velocity. Older tutorials also use Input.GetAxis("Horizontal"), which needs the legacy input setting under Project Settings, Player, Active Input Handling.

Script 2: a simple score keeper

using UnityEngine;

public class ScoreKeeper : MonoBehaviour
{
    public static int Score;
}

static means there is one shared Score for the whole game. It is fine for a first project; later you’ll replace it with events or a game manager.

Script 3: the coin

using UnityEngine;

public class Coin : MonoBehaviour
{
    [SerializeField] private int value = 1;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            ScoreKeeper.Score += value;
            Debug.Log("Score: " + ScoreKeeper.Score);
            Destroy(gameObject);
        }
    }
}

OnTriggerEnter2D is another method Unity calls for you, the moment something enters the coin’s trigger. Debug.Log prints to the Console, which is your best friend while learning.

Turn the coin into a prefab

Drag one finished coin from the Hierarchy into your Project window. It becomes a prefab: a reusable template. Change the prefab and every coin updates. You can also create coins from code:

[SerializeField] private GameObject coinPrefab;

void SpawnCoin(Vector2 position)
{
    Instantiate(coinPrefab, position, Quaternion.identity);
}

Instantiate creates a copy and Destroy removes one. Those two calls drive bullets, enemies, pickups and particle effects in nearly every game.

Collisions vs triggers

Beginners often mix these up:

  • Collision (OnCollisionEnter2D): two solid objects bump. The player lands on a floor, a ball hits a wall.
  • Trigger (OnTriggerEnter2D): one collider is a sensor with Is Trigger ticked. Things pass through it and your code reacts: coins, checkpoints, damage zones.

For either event to fire, at least one of the two objects needs a Rigidbody2D, and both need colliders. 3D games use the same methods without the “2D”.

Common errors and what they mean

  • NullReferenceException: a variable points to nothing. Check the Inspector for an empty slot, or a GetComponent call that found nothing.
  • “Can’t add script”: the class name and file name don’t match, or the script has a compile error.
  • Trigger never fires: Is Trigger isn’t ticked, there’s no Rigidbody2D, or you mixed 2D and 3D components.
  • CompareTag does nothing: the tag is spelled differently in the editor, or it isn’t assigned.
  • Movement differs between devices: you forgot Time.deltaTime, or you’re moving a Rigidbody in Update.
  • Changes vanish after Play: values edited in Play mode reset when you stop. Edit them after stopping.

A three-week practice plan

  1. Week 1: variables, if statements and methods. Make a cube that changes colour on a key press and a timer that counts down in the Console.
  2. Week 2: the coin collector above, then add a jump with a ground check and a “You win” message when the score reaches ten.
  3. Week 3: add a moving enemy that resets the level on contact, a spawner that uses Instantiate, and a simple UI score label.

Change something in every tutorial you follow. Copying code teaches typing; changing it teaches C#. Once you’re comfortable, our Unity game developer roadmap shows what to learn next, and if you’re still choosing an engine, read Unity vs Unreal vs Godot.

Your C# for Unity checklist

  • I can explain what a component is and why scripts are components
  • I use [SerializeField] private for Inspector values
  • I read input in Update and move Rigidbodies in FixedUpdate
  • I use Time.deltaTime for frame-based movement
  • I can tell a collision from a trigger
  • I’ve made a prefab and spawned it with Instantiate
  • I read the Console before asking for help
  • My project is in Git

Learn it with Omebly

Omebly Academy’s Game Development course is live and mentor-led online, with recordings and weekly one-to-one reviews. Month one covers Unity basics, C# fundamentals, scenes, prefabs, input and 2D movement; month two adds physics, collisions, UI, scoring, audio and simple enemy AI; month three covers level design, game feel, animation and building for Android and PC. Tools include Unity, C#, Visual Studio, Blender basics, Aseprite or Photoshop, Git and itch.io.

Tracks are Core ($699, 3 months), Professional ($1,199, 6 months, adding 3D games, cameras, lighting, save systems and optimisation) and Career ($1,999, 12 months, adding multiplayer basics, a publishing pipeline and a polished portfolio game). You get an Omebly certificate of completion, and placement assistance is support, not a job guarantee. If you’d rather have a game built for your business, see our Unity game development service.

Stuck on your first script? Message us on WhatsApp or contact us for a free first call.

Frequently asked questions

Do I need to learn C# before starting Unity?

No. Most beginners learn C# and Unity together. Learn the basics (variables, if statements, methods and classes) as you build small scenes, rather than finishing a full C# course first. A few hours of plain C# practice does help, though.

How long does it take to learn enough C# for Unity?

With regular practice, most beginners can write simple movement, scoring and collision scripts within four to six weeks. Comfort with bigger systems such as saving, menus and enemy AI usually takes a few months of building small games.

Is C# hard for a complete beginner?

C# is stricter than Python because you declare types and end lines with semicolons, but that strictness helps: the editor catches many mistakes before you press Play. Most beginners find it manageable within a few weeks.

What is the difference between Update and FixedUpdate?

Update runs once per rendered frame, so it suits reading input and simple logic. FixedUpdate runs on a fixed timestep used by the physics engine, so it is the right place to change Rigidbody velocity or apply forces.

Why do I keep getting NullReferenceException in Unity?

It means your script is using a variable that points to nothing. Usually a field was not assigned in the Inspector, GetComponent did not find the component, or the object was destroyed. Double-click the error in the Console to jump to the exact line.

Can I use Visual Studio Code instead of Visual Studio for Unity?

Yes. Unity works with Visual Studio, Visual Studio Code and JetBrains Rider. Install the matching Unity extension or package so you get autocomplete and error highlighting for Unity's own classes.

Written by

Nazmul Hussain, Managing Director & Technical Head, Omebly. 10+ years building websites and apps for clients in India, the Gulf, the UK and the US, and mentoring at Omebly Academy. LinkedIn · GitHub