Skip to main content
Unity 3D Basics – Complete Beginner to Advanced Guide
CHAPTER 05 Beginner

C# Scripting Basics in Unity

Updated: May 16, 2026
30 min read

# CHAPTER 5

C# Scripting Basics in Unity

1. Introduction

A beautiful 3D environment is just a digital diorama until you write code. Programming is the soul of video games. It allows you to define rules: *If the player presses 'Jump', apply upward force. If health reaches zero, play an explosion and restart the level.* Unity uses the C# (C-Sharp) programming language. If you have never written a line of code before, don't worry. Game logic is incredibly logical. In this chapter, we will master C# Scripting Basics in Unity. We will learn how to create a script, understand the MonoBehaviour blueprint, declare variables, write custom functions, and use the Start and Update loops.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Create and attach C# scripts to GameObjects.
  • Understand the using tags and the MonoBehaviour class.
  • Declare variables (int, float, bool, string).
  • Differentiate between the Start() and Update() methods.
  • Write custom functions to organize code.
  • Print debugging messages to the Unity Console.

3. Creating and Attaching a Script

  1. 1. In the Project window, right-click -> Create -> C# Script.
  1. 2. CRITICAL: Name it immediately (e.g., PlayerLogic) and press Enter. Do not click away! The file name must exactly match the class name inside the code.
  1. 3. Double-click the script to open it in Visual Studio.
  1. 4. To make the script run, drag the script file from the Project window and drop it onto a GameObject (like your Player) in the Hierarchy. It is now a Component!

4. Anatomy of a Unity Script

When you open a new script, Unity provides a template:
csharp
123456789101112131415161718
using UnityEngine; // Tells the script to use Unity's built-in code library

// The class name MUST match the file name!
// ": MonoBehaviour" means this script can be attached to a GameObject.
public class PlayerLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

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

5. Variables (Storing Data)

Variables are boxes that hold information. In C#, you must declare the *type* of box.
  • int: Whole numbers (1, 5, -10). Good for health or score.
  • float: Decimal numbers (3.14f, 5.0f). Always end with an 'f'. Good for speed or time.
  • bool: True or False. Good for isDead or isGrounded.
  • string: Text ("Hello World"). Good for player names.

*Making a variable public allows you to change its value directly in the Unity Inspector without opening the code!*

csharp
123
public int playerHealth = 100;
public float moveSpeed = 5.5f;
public bool hasKey = false;

6. Start() vs. Update()

Unity controls when your code runs using special event methods.
  • void Start(): Runs exactly ONCE, the moment the object is spawned (or the game starts). Use this to set up starting values or find other objects.
  • void Update(): Runs continuously, once every single frame (e.g., 60 times a second). Use this to check for player input or move objects.

7. Functions (Organizing Code)

Don't put thousands of lines of code inside Update(). Create custom Functions (also called Methods) to group code into reusable blocks.
csharp
1234567891011121314
void Update()
{
    if (playerHealth <= 0)
    {
        Die(); // Call the custom function
    }
}

// A custom function
void Die()
{
    Debug.Log("Player has died!");
    Destroy(gameObject); // Deletes the object from the game
}

8. Debugging to the Console

If you don't know what your code is doing, print a message to the Unity Console window! Debug.Log("The variable value is: " + playerHealth); If a line of code has an error (like a missing semicolon ;), the Console will print a red error and tell you the exact line number where the problem is.

9. Best Practices

  • Use [SerializeField] instead of public: Making a variable public exposes it in the Inspector, but it also allows any other script in the game to change it. A better practice is to make it private (so other scripts can't break it), but add [SerializeField] above it. This magical tag forces Unity to show it in the Inspector anyway!
[SerializeField] private float jumpHeight = 10f;

10. Common Mistakes

  • The Class Name Mismatch: If you create a script, click away, and then rename the file to EnemyAI, the code inside will still say public class NewBehaviourScript. Unity will throw a massive error and refuse to let you attach the script. The file name and the class name MUST be identical!

11. Mini Project: The Console Calculator

Objective: Write a script that uses variables, Start, and custom functions.
  1. 1. Create a script named Calculator. Attach it to the Main Camera.
  1. 2. Open it and write the following code:
csharp
12345678910111213141516171819
using UnityEngine;

public class Calculator : MonoBehaviour
{
    public int damage = 15;
    public int currentHealth = 100;

    void Start()
    {
        Debug.Log("Game Started. Health is: " + currentHealth);
        TakeDamage(); // Call the function once
    }

    void TakeDamage()
    {
        currentHealth = currentHealth - damage;
        Debug.Log("Ouch! Took damage. New Health: " + currentHealth);
    }
}
  1. 3. Press Play in Unity and watch the Console output!

12. Practice Exercises

  1. 1. What does the f at the end of 5.5f represent in C#?
  1. 2. Why is it dangerous to put a command like "Spawn an Enemy" directly inside the Update() loop without an if statement?

13. MCQs with Answers

Question 1

In a Unity C# script, which method is automatically executed exactly once when the GameObject is first loaded into the scene?

Question 2

To allow a Game Designer to easily tweak a player's movement speed using the Unity Inspector panel, without opening Visual Studio, how should the programmer declare the variable?

14. Interview Questions

  • Q: Explain the inheritance requirement for a C# class to be attached to a Unity GameObject as a Component. What base class must it inherit from?
  • Q: Contrast the execution frequency of the Start() method versus the Update() method. Give an example of code that belongs in each.
  • Q: A junior developer renames a C# script file in the Unity Project window from Bullet to Missile. Suddenly, the script won't compile, and Unity throws an error. Why did this happen, and how do you fix it?

15. FAQs

Q: Do I need to memorize all the C# syntax? A: No! Every professional programmer Googles things daily. If you forget how to write an if statement or how to find an object, simply search the Unity Documentation. Memorize the *concepts*, not the syntax.

16. Summary

In Chapter 5, we became programmers. We learned that C# scripts are just custom Components we attach to GameObjects. We explored the anatomy of a MonoBehaviour script, declaring variables (int, float, bool) to store data, and exposing them to the Inspector. We discovered that Start() is for initialization and Update() is for continuous frame-by-frame logic. Finally, we learned to organize our code with custom functions and hunt down bugs using Debug.Log.

17. Next Chapter Recommendation

We know how to write code. Now let's use code to read the player's keyboard and move an object across the screen! Proceed to Chapter 6: Player Movement and Input Systems.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·