Skip to main content

Anatomy of Unity C# Scripts

In Unity game engine, C# scripts are used to add logic and behavior to game objects. Here is a basic anatomy of a C# script in Unity:

  1. Namespace Declaration:

A C# script usually starts with a namespace declaration, which is a container that groups related code elements, such as classes and functions, into a named scope. For example:

image.png


  1. Class Declaration:

Within the namespace, the script should contain at least one class declaration, which defines the behavior and properties of a game object. For example:

image.png

 

  1. Variables:

The class may contain variables, which are used to store data that can be accessed and modified by the class's methods. Variables can be declared as public, private, or protected, depending on their accessibility. For example:

image.png

  1. Methods:

The class may also contain methods, which are functions that define the behavior of the game object. Methods can be declared as public, private, or protected, depending on their accessibility. For example:

image.png

  1. Start and Update Methods:

Two special methods that are commonly used in Unity scripts are the Start() and Update() methods. The Start() method is called once when the game object is created, and the Update() method is called once per frame. These methods can be used to initialize variables, update the game object's position, or interact with other game objects. For example:

image.png

image.png

  1. Event Functions

The class may contain event functions, which are special methods that are automatically called by Unity in response to certain events, such as collisions, triggers, or input. For example:

image.png

This code will decrease the game object's health by 10 if it collides with an object tagged as "Enemy".