Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท C# Scripting

Your First C# Script

Write your first Unity C# script: create it, understand the MonoBehaviour template, attach it, log to the Console, handle errors, and test the logic with a runnable plain C# stand-in.

Scripts are where your game becomes yours. A Unity script is a C# file that defines a class deriving from MonoBehaviour; when you attach it to a GameObject it becomes a component that Unity can call. In this lesson you create a script, read every line of the template, make it print to the Console and move an object, and learn to read the most common errors.

The Unity script blocks are read-only here. The runnable blocks reproduce the logic in plain C# so you can experiment with the language part: classes, fields and methods.

Create and attach a script

  1. In the Project window, right-click the Scripts folder and choose Create > MonoBehaviour Script (or C# Script in older versions).
  2. Type the name immediately, for example HelloUnity, and press Enter. The file name must match the class name exactly, including capitals.
  3. Double-click it to open your code editor.
  4. Drag the script onto a GameObject in the Hierarchy (or use Add Component in the Inspector).

Unity compiles scripts whenever you save and return to the editor. A spinning icon in the bottom right shows that it is compiling.

The template, line by line

C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloUnity : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}
  • using UnityEngine; imports the Unity API: MonoBehaviour, Vector3, Debug, Time, and so on. The two System.Collections lines are only needed for coroutines and lists and are often removed.
  • public class HelloUnity : MonoBehaviour declares a class that derives from MonoBehaviour. Only classes that derive from it can be attached to GameObjects.
  • Start and Update are event methods (also called messages). You do not call them; Unity finds them by name and calls them. They are usually private (no access modifier), which is fine.
  • Unity ignores methods with other names, so a typo like update() or Updat() simply never runs. Check capitalization when "nothing happens".

Logging to the Console

Debug.Log writes text to the Console window, the standard way to see what your code is doing:

C#
using UnityEngine;

public class HelloUnity : MonoBehaviour
{
    void Start()
    {
        Debug.Log("Hello, Unity!");
        Debug.Log("I live on: " + gameObject.name);
        Debug.LogWarning("This is a warning (yellow).");
        Debug.LogError("This is an error (red).");
    }
}

Press Play and open the Console (Ctrl+Shift+C). You will see four lines. Click a line to see the stack trace, and double-click it to open the code. Debug.Log accepts a second argument, a context object, that highlights that object in the Hierarchy when you click the message: Debug.Log("hit", gameObject);.

Use string interpolation to build messages: Debug.Log($"Health is {health}");. It is easier to read than + concatenation.

Making something happen: Update

Add movement. This script moves its GameObject to the right at two units per second:

C#
using UnityEngine;

public class SlideRight : MonoBehaviour
{
    public float speed = 2f;

    void Update()
    {
        transform.Translate(Vector3.right * speed * Time.deltaTime);
    }
}

transform is a shortcut to this object's Transform component, Translate moves it (in local space by default), and Time.deltaTime makes the speed independent of the frame rate (see the game loop). Because speed is public, you can change it in the Inspector without opening the script.

Types you use every day

C# type Used for
int Whole numbers: score, lives, ammo
float Decimals; literals need an f suffix (2.5f)
bool True/false flags: isGrounded, isDead
string Text
Vector2, Vector3 Positions, directions
GameObject, Transform, Rigidbody... References to objects and components

The f matters: in C#, 2.5 is a double, and Unity's API uses float. Writing float speed = 2.5; gives an error "cannot implicitly convert type double to float".

Experiment with the logic in plain C#

A script is a class with fields and methods. This stand-in makes a Counter class and "calls Update" on it, to show how state persists between calls and how a field acts as a setting.

C# A script as a class (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice how frames keeps growing across Update calls: fields persist, local variables do not. That is why you use a field whenever a value must survive from one frame to the next.

Float pitfalls and the f suffix

Another stand-in shows the type difference that causes the most common compile error, and how float precision behaves.

C# float versus double (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Comparing floats with == is unreliable. Unity offers Mathf.Approximately(a, b) for that. You will use it rarely, but it prevents a class of mysterious bugs.

Reading compile errors

When you save a script with a mistake, the Console shows a red message such as:

TEXT
Assets/Scripts/HelloUnity.cs(8,17): error CS1002: ; expected

Read it as: file, (line, column), error code, description. Fix errors from the top: one missing semicolon can cause a dozen follow-up errors. Common ones:

  • CS1002 ; expected: a missing semicolon.
  • CS0103 name does not exist: a typo, or a missing using.
  • CS0246 type or namespace not found: missing using UnityEngine; or a misspelled class.
  • "The script class cannot be found"/ "no MonoBehaviour scripts in the file": the file name and class name differ.
  • CS0117/CS1061: the member does not exist; check the spelling or the API version.

A script with a compile error stops Unity from entering Play Mode. Fix all red errors in the Console first, since a single error blocks every script in the same assembly.

Good habits from day one

  • One class per file, named like the file.
  • Use PascalCase for classes and methods, camelCase for fields and locals.
  • Keep scripts small and focused: PlayerMovement, PlayerHealth, not PlayerEverything.
  • Make tunable values public or [SerializeField] private (see Inspector fields).
  • Comment why, not what.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A script is attached to a GameObject but its Start method never runs. Which is a likely cause?

    Unity finds event methods by exact name, so start() is just an ordinary method it never calls.
  2. 2. Why is float speed = 2.5; a compile error?

    Decimal literals are doubles by default. Add f for floats.
  3. 3. Which base class lets a script be attached to a GameObject?

    MonoBehaviour is the base class for scripts attached to GameObjects. ScriptableObject is for data assets that are not attached.
  4. 4. Where should you start reading when the Console shows many compile errors?

    Early errors often cause later ones, so fix from the top.

Summary

  • A script is a C# class deriving from MonoBehaviour; the file name must match the class name.
  • Start and Update are event methods that Unity calls by name.
  • Debug.Log writes to the Console; use it constantly while learning.
  • Use float with the f suffix; public fields appear in the Inspector.
  • Fix compile errors from the top; a compile error blocks Play Mode.

Next: Lifecycle Methods: Awake, Start, Update and More