Creating a custom component in Unity

Unity provides a ton of components out-of-the-box and each main release adds a ton more. Yet, no matter how many components are released, there will never be enough to satisfy your specific needs. For this reason, you’ll need to create your own components. This is where scripting comes into play.

For the non-programmer, at best, scripting is a small barrier to entry. At worst, scripting is the devil that never sleeps.

Coming from an arts background, I can say that scripting is not as hard as you might imagine. Like anything, it just requires some time and patience to understand how it works.

Note: This tutorial is part of a collection that teaches Unity development from the ground up. You can read the entire series over here. This series is free and does not require any account creation. All assets are provided. If you find it useful, feel free to buy me a coffee.

In this book, you’ll write scripts in C#, which is a popular language developed by Microsoft that works for both mobile and desktop apps. It’s feature-rich and fully versatile. Unfortunately, I can’t teach it all within the covers of this book.

Thankfully, you can find an entire free course here. It’s designed for non-programmers and taught within the context of Unity.

If you’re a beginner to programming, definitely check that out first. If you’re an experienced developer, or a particularly brave beginner, feel free to continue along, since everything in this book is step-by-step; just understand that there may be some gaps in your understanding without C# knowledge.

Thinking like a script

In Unity, you create a script like any other asset, and this script can be added to any GameObject. You can add different fields, allowing users to customize the script inside the editor.

A script derives from a class called MonoBehaviour. This class is the glue that connects C# with Unity. It is the only class that attaches to GameObjects. If you try to attach a regular class to a GameObject, you’ll get an error. That said, you access regular C# classes inside a MonoBehaviour class.

You can override several MonoBehaviour methods to get notified upon certain events:

  • Update(): This event occurs at every single frame. If your game runs at sixty frames per second, Update() is called sixty times. Needless to say, you don’t want to do any heavy processing in this method.
  • OnEnable(): This is called when a GameObject is enabled and also when an inactive GameObject suddenly reactivates. Typically, you deactivate GameObjects when you don’t need them for a while but will have a need at a later point in time.
  • Start(): This is called once in the script’s lifetime and before Update() is called. It’s a good place to do setup and initialization.
  • Destroy(): This is called right before the object goes to the GameObject afterlife. It’s a good place to do clean up, such as shutting down network connections.

There are many other events that you’ll discover throughout this book. To see a complete listing, head to the MonoBehavior reference on Unity’s site:

https://docs.unity3d.com/ScriptReference/MonoBehaviour.html

Creating your first script

You have many options for creating a script. You could click the Add Component button and then select New Script. But try it this way: Select the Scripts folder in the Project window, and then click the Create button (plus sign). Select MonoBehaviour Script from the drop-down menu and name it PlayerController.

This shows the Project window with the create item (plus sign) selected.

You’ll see that your new script in the Scripts folder. Drag it from the Scripts folder onto the SpaceMarine GameObject.

This shows the SpaceMarine GameObject with your new compnent attached.

You’ve added your first custom component! Granted, it doesn’t do anything… yet. It’s time to roll up your sleeves and write your first lines of code.

Creating some fields

Components provide a lot of customization, and they do this through fields. Unity allows you to create all sorts of fields in your components that allow users to type into it or even drag other GameObjects into it.

To get started, double-click your PlayerController script. This will open your code editor. It will already have code in it.

This shows Visual Studio Code with a new script open.

First, expose the player’s name to the editor. Add the following just inside the class definition, underneath the open curly brace.

Note: If you are new to programming languages, it’s critical that you copy everything exactly as it is written. Any deviation will produce errors. Programming languages are very precise and become grumpy when you use the incorrect case or syntax. If your script throws an error, carefully review the code to make sure you didn’t miss, forget or mess up something.

[SerializeField]
private string playerName;

It should look like the following:

This shows your new code added to the script

The [SeralizeField] is a Unity attribute that exposes the playerName to the editor. In essence, this creates a text field.

Save. Switch back to Unity. Unity detects a change in the script and then compiles your script. Select the SpaceMarine. You’ll see a new field in the Inspector.

This shows the Player Name in the Unity editor.

Also, notice the field is two words inferred from the variable name. This is why it is so important to follow coding conventions. Switch back to your code editor. Add the following beneath the previous code.

[SerializeField]
private GameObject spawnPoint;

[SerializeField]
private Camera mainCamera;

This time you added a GameObject field followed by a component field. This gives you access to their properties in code. Mind you, there are plenty of ways to access Unity objects in your code. Save and switch back to Unity.

Select your Space Marine. You’ll see your new fields. Drag a Spawn point into the Spawn Point field. Next, drag the Main Camera into the Main Camera field. It will look like the following:

This shows the two new fields in the Unity editor.

Notice that the Main Camera field was a component field, yet you dragged a GameObject into it. In that case, Unity saw that the Main Camera GameObject had a camera component, and referenced it. Try dragging the Directional Light to the field. You’ll discover that you won’t be able to add it since it doesn’t have the camera component.

Where to go from here

You’ll be spending a lot of time writing your own custom components. In the remaining chapters, you’ll be writing a lot of code. Just keep in mind, the following chapters will not be spending much time explaining C#.

For example, if you do not know the difference between a string and an int, then take the time to watch my free Beginning C# with Unity course. It will teach you everything you need to know to follow along with this book.

You’ll write some more code soon enough, but first, you need to understand Unity’s input system. You’ll do this in the next tutorial.


Discover more from Jezner Blog

Subscribe to get the latest posts sent to your email.

By Brian Moakley

Brian Moakley is a writer and editor who lives amongst the quiet hills in New England. When not reading tales of high adventure, he is often telling such stories to all who will listen.

Related Post

Leave a Reply