Course contentsShow
← Unity Game Development
Lesson 14 of 8281. Unity FoundationsFree lesson

Implementing Logic via Custom Script Components

Create and attach C# scripts to GameObjects to define unique behaviors that extend the engine's built-in functionality.

In this lesson, you will learn how to breathe life into your GameObjects by writing your own C# scripts to define unique behaviors that go beyond Unity’s built-in tools.

The Power of Custom Logic

Up until now, you have used pre-built components like Transform or Mesh Renderer to manage how your objects look and move. However, Unity cannot know that you want a specific door to open only when a player approaches, or that a coin should spin. This is where Custom Script Components come in.

In Unity, a script is essentially a blueprint for a new component. When you create a C# script, you are defining a new "behavior" that you can drop onto any GameObject, just like you would add a Rigidbody or a Light.

Creating Your First Behavior

To create a script, right-click in your Project Window, select Create > C# Script, and give it a name (e.g., SpinningObject). When you double-click it, your code editor will open. You will see a structure that looks like this:

using UnityEngine;

public class SpinningObject : MonoBehaviour 
{
    void Update() 
    {
        // Your custom logic goes here!
        transform.Rotate(0, 1, 0);
    }
}

The Update() method is a special instruction that tells Unity to run the code inside those brackets once every single frame. Because this script inherits from MonoBehaviour, Unity recognizes it as a component.

Attaching the Logic

Writing the code is only half the process. For this logic to actually execute, the script must be attached to a GameObject in your Hierarchy. You do this by dragging the script file directly onto the GameObject or by clicking the Add Component button in the Inspector and searching for your script’s name.

Once attached, the script appears in the Inspector as a new component. The moment you press Play, Unity reads the instructions in your script and applies them to that specific object. You are no longer just arranging a scene; you are now programming how your game world functions.

Key Takeaway: Custom scripts act as personal instructions for your GameObjects, allowing you to define unique rules and behaviors that extend Unity's built-in functionality.