Partial class and Unity

Partial classes are fine with Unity… you just need to have at least one file named precisely as your class.

I always make that the one file that inherits MonoBehaviour but I’m not sure of that being a requirement.

For instance, I was lazy with my Jetpack Kurt Space Flight primary player controller and right now most of it is in one giant class, spread across several files that handle “areas of concern.” Right now I am experiencing zero pain, so why refactor?

I even went so far as to put all those files in their own directory, which goes with the scene. (I use LOTS of partial scenes too, all additively loaded on top of each other.)

7170964--859327--Screen Shot 2021-05-24 at 9.33.33 AM.png

The only purpose is for organization, but I also use it as a precursor to breaking up and refactoring a class: if a class grows too large, try physically dividing the code BEFORE you tear it apart into two classes, and partial classes let you engineer this on the fly.

Just beware that Unity uses the GUID for your script to connect it to assets, and in the case of partials, it uses the GUID of the main root file.

Some info about Missing script warnings, GUIDs, renaming GUIDs, etc:

Warning: you may encounter folks who express a blind reflexive hatred for partial classes, much like what you find for other incredibly useful constructs such as singletons. I have yet to hear even one coherent reason that isn’t simply a minor footnote to how useful such constructs are for actual real world development. It seems like it’s an academic knee-jerk response or something, so be prepared for it. Besides, remember it’s SOFTware, so it’s SOFT, and you can refactor it at any time you like.

When I’m actively working I will often make a single empty file suffixed with _ as a “seed” that I can clone each time I need to make a new partial, to save retyping and refactoring, and especially if I already have a namespace going… saves a TON of time, looks like this:

7170964--1322807--Screenshot 2023-10-26 at 4.33.57 PM.png 7170964--1322804--Screenshot 2023-10-26 at 4.34.02 PM.png

1 Like