Create a Custom C# Script
Last updated
Last updated
When we want to create a C# script to create or modify behaviors of a game object, the most common approach is to have our custom class inherit from MonoBehaviour. Most of the code that we write for this course will end up being attached to gameObjects within the Unity Editor.
Note: there are other ways to have custom code integrated within Unity, we'll look at these other approaches later in the course.
To create a custom script component, create a folder name it 'Scripts' within your Project Panel's Asset folder. Next, create a C# script by right-clicking inside within the 'Scripts' folder, select the top menu option: C# Script. Name your file Example Insure that the script's Filename is spelled the same as the Class name, otherwise Unity won't allow the script to be added as a component to a game object.
The code section below is a very basic C# script, Example.cs. This creates a C# class Example
, which inherits from the MonoBehavior
class. When creating a C# script object, some code is automatically generated in the file when it's created, this includes the MonoBehaviour Start() and Update() functions, the Debug.Log() content has been added to the following script to create custom behavior. The Unity Editor console will display the Debug.Log messages, and any code errors.
In the image below, we select the main camera in the Hierarchy panel, then in the inspector panel we select Add Component, then we select Scripts This lets us select the script that we've already created. When we push play, the script is executed and we see the Debug.Log()
output in the console panel. The Console provides a good way to get information about our program during its execution.