MonoBehaviour Classes (MBs) and Pure C# Classes (POCOs)
Objective: Learn how to make the best design choices for your game with a mixture of MBs and POCOs.
When do I use MBs and when do I use POCOs?
MonoBehaviour Classes (MBs)
It makes sense to use MBs when your script needs to operate on a Scene object. It’s attached to a game object and that’s very important, architecturally. That means that the script can interact with that game object and any other scripts or components on it.
Like with a Pet class, your pets are going to have functionality and they should be MBs because they’ll most likely have 3D models, character traits, and they’ll have functionality that’s present on the game object. For example, with the 3D model, you may have a Mesh Filter and Skinned Mesh Renderer component. You may also have other MB scripts that help the Pet perform actions.
Pure C# Classes (POCOs)
Pure C# Classes do not inherit from MB and are most useful if, for example, you want to be able to instantiate and initialize an object you create with a constructor. MBs have more fields/properties/memory allocated that you might not always need for every class/struct you create in your codebase. POCOs are also serialized differently and you’ll need to mark the class as [System.Serializable] at the top of every POCO to have it serialized and visible in the Unity Editor.
The main difference of a POCO is that it cannot stand on its own in Unity and it needs a Unity object to be contained within. Here is an example of that:
private class Enemy : MonoBehaviour {
[SerializeField] private HealthStatus health = new();
}
[Serializable]
private class HealthStatus {
[SerializeField] private int hp;
[SerializeField] private int maxHP;
}
It all comes down to experience and what feels right. If it feels right to take a MonoBehaviour and turn it into a POCO, go for it. But for the most part, you should be using POCOs to define custom blueprints for your Classes.