Game Development
Your first C# script
Learn to create a new C# script in Unity and attach it to a GameObject.
Your First C# Script
We create C# scripts to write game logic and object behaviors in Unity. You can create a new script file by right-clicking in the Project window and choosing Create > C# Script. The name of the created file and the name of the class inside it must match exactly.
public class Player : MonoBehaviour
{
// Game code goes here
}
If the file name and class name do not match, Unity cannot attach the component to an object and produces a compilation error.
Attaching a Script to an Object
For a C# script to execute in the scene, it must be attached to a GameObject as a component. You can drag and drop the script from the Project window onto the object in the Hierarchy. Alternatively, select the object and click the Add Component button in the Inspector to search and add the script.
// Inspector > Add Component > PlayerController
// The script is now a component of the object
A script that is not attached to any GameObject in the scene will not run when the game starts.
Exercise Run your first script class
Inside the Start method of the PlayerScript class, print the message "PlayerScript calisiyor!" using Console.WriteLine.
Show example solution
using System;
public class PlayerScript
{
public void Start()
{
Console.WriteLine("PlayerScript calisiyor!");
}
}
public class Program
{
public static void Main()
{
PlayerScript player = new PlayerScript();
player.Start();
}
}
Test yourself
-
What must be the relationship between the file name and class name when creating a new C# script in Unity?
- The file name can be arbitrary, only the class name matters.
- The file name and class name must be different from each other.
- The file name and class name must match exactly.
- The class name must start with lowercase, the file name with uppercase.
Show answer
The file name and class name must match exactly. — Unity requires the file name and the class name inside it to match exactly in order to recognize the script file as a component.
-
MonoBehaviour base class
public class PlayerController : ____
{
}
Show answer
public class PlayerController : MonoBehaviour
{
}
-
Script creation and attachment steps
- Project penceresi
- Where the new C# script is created
- Add Component
- Adds the script to the selected object
- MonoBehaviour
- Base class Unity scripts inherit from
- Sürükle-bırak
- Dragging a script onto a scene object
Next lesson: using and namespace