Saving Memory with C# Structs

In C++, there’s very little difference between a class and a struct: a class defaults to private access and a struct defaults to public access. There are no other technical differences between the two, though by convention, they are often used for different things.

C# is a language that mimics the syntax of C++ to some degree, and also has class and struct. However, in this case, the technical difference is quite large! In this post, I’ll briefly explain that difference and highlight a scenario where using a struct saved me a lot of memory on a project I’m working on.

[Read More]

When to Inherit from MonoBehaviour

When you create a new C# class in Unity, it automatically inherits from the MonoBehaviour class, which is Unity’s base class for components. In Unity, you tend to create a lot of components, but it’s important to keep in mind that you don’t have to.

When I was new to Unity, I thought everything should inherit from MonoBehaviour - that’s just how you work in Unity! Some of my students have also had this misconception. In fact, there are often scenarios where it makes more sense to not inherit at all, or to inherit from another base class. This post explains situations where it makes sense to use MonoBehaviour, and some cases where you’d be better off without it.

[Read More]

Encapsulate Unity Inspector Variables

When writing a Unity component, it’s likely that you’ll want to expose some variables in the Unity Editor’s Inspector, so that either you or a designer can modify those values without having to recompile the script. However, the default method of exposing variables in the inspector can break class encapsulation in an undesirable way. This post explores ways to expose variables in the Inspector without sacrificing your class’s encapsulation.

[Read More]