- Home /
Static Initialization
Is there any way to achieve static initialization in Unity?
Java allows you to do this within a class (static block):
static { // code }
C# allows you to do this within a class (static constructor):
static MyClass() { // code }
However, in Unity the static constructor only seems to get called after recompilation. This is the same as normal constructors then; but while we have Awake() to replace those, I'm unaware of anything that can be used for static initialization.
What would I use it for? Well, there's a bunch of design patterns that I'm aching to use in my game, such as Pluggable Factory. That pattern relies on the fact that subclasses of a product class can register themselves with a Maker before it is used to construct anything.
Using Pluggable factories allows you to specify any number of additional product subclasses without having to alter the code of the Maker that produces them, which means it is very easily to extend a framework with additional functionality.
Answer by Mike 3 · Jun 14, 2010 at 08:58 PM
You can use normal, non-monobehaviour classes with unity
This lets you use the static constructor for your factory without any problems
That way you can instantiate all your factories from a monobehaviour, and they'll all work without issue
Actually, that is what I'm doing. However, a class' static constructor only seems to be called after I've made a change in that class' code to force recompilation...
At least, that is how it seems to work in the editor. I haven't tested it with built executables.
"That way you can instantiate all your factories from a monobehaviour, and they'll all work without issue"
Wait, are you suggesting using a monobehaviour to call initialization routines on all the factories? That could work, but it kind of violates encapsulation. You then still need an external class to know about all subclasses, which forces additional maintenance, which means they're not very 'pluggable'.
Or am I missing something? I might be confusing some things..
I was actually proposing your subclasses weren't $$anonymous$$onoBehaviours either (You could send in a GameObject as a dependency to the constructor or an inherited function if you need it to act on something). Obviously that isn't always a viable solution though. Re. your first comment - the static constructor should work fine in a built player
Your answer
![](https://koobas.hobune.stream/wayback/20220613062125im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
class constructor/order/initialization confusion 1 Answer
Is it possible to control the order of a static's initialization? 2 Answers
What the best way to initialize constant static data in a MonoBehavior? 0 Answers
Design pattern: Loading custom data into prefab objects 0 Answers
Assigning a GameObject Script Variable Before Start is Called 1 Answer