top of page
  • Will Hendrickson

Encapsulation in Unity

In Unity, there are many ways to code a game. You can create a GameManager class and reference it directly, you can create your own data assets using ScriptableObject, and now you can even use the powerful Entity Component System to create highly performant, multi-threaded code.

But should you?

As ECS gains popularity and many project managers and lead programmers are switching over, I have decided to only upgrade a hand full of components to this new system.

The main reason for this is encapsulation. Currently, MultiGame Pro has over 170 complete scripts in it, and I have been very careful to keep them all separated so that there are as few interdependencies as possible. Because of this, I am able to easily change or replace components without breaking backwards-compatibility. Additionally, all of the components use a custom event system that separates the method call from the reference. This way I can even swap out components at runtime and the game will continue to function correctly!

If I were to switch to the ECS, I would lose a lot of this encapsulation. To take full advantage, I would separate entity data from implementation, and batch all processing together to allow for threading across multiple instances. This also lends itself to strong-coupling between components, their managers, and each other.

In some cases this is fine or even desirable. For my zombie AI, currently supporting 256 concurrent agents, I could see at least 4x or 10x increase in performance by using the ECS, allowing developers to create much, much larger hordes!

But for most of the systems in MultiGame, this doesn't make sense. Instead, I want to keep things modular so that MultiGame users can freely experiment without worrying about breaking their game after an update. I can also handle a much larger and complex code base this way: because everything is encapsulated and fully modular, it's easy to make sweeping changes to one or several game systems without worrying about breaking other stuff.

So when you're deciding whether or not to use ECS, weigh the benefits and costs against each other. Realize that it's not a straight upgrade, and that in many situations regular old monobehaviours are the way to go.

If you enjoyed reading this article and would like to get weekly posts like this one, please subscribe to our mailing list! We will keep you informed on techniques, insights and best practices in Unity game development!

bottom of page