I’ve recently come across the absolutely wonderful design pattern called ‘Pluggable Factory’. This design pattern allows you to decouple a factory from knowledge of subclasses of the thing it produces.
There’s a whole bunch of uses. You can use them to build a minimal-maintenance framework for functionality that you’ll be continuously extending with loads of subclasses, like messages, events and rules. As a test I would like to use it for serializing/de-serializing some messages over the network.
The trick is that each subclassed factory uses a static initialization routine to register itself with a single ‘Maker’ before the program’s main function starts.
The problem is that I cannot get static initialization to work in Unity. Static constructors don’t seem to get called at all! I know I’m not supposed to use object constructors because they can be called randomly in-editor, but static constructors should be a different story. Since Awake() can be used to replace a constructor I was hoping there was also something similar to replace the static constructor (for class initialization). Is there such a thing? Or is there a hack to get around it?
I know this is ancient but I’d really like to know if this is doable in-game (yet). I see according to this you can do it in the editor, but I’ve found nothing that makes static constructors even run in gameplay mode or a build.
Maybe I’m not getting something. Do you have to have them in a Monobehaviour and attached to a gameobject in-scene to run? I just tried that and it did work, but I expected to be able to use them from a class not in a Monobehaviour.
Example: A.cs is attached to a game object in scene. Play is pressed in the editor.
using UnityEngine;
using System.Collections;
public class A : MonoBehaviour {
static A() {
Debug.Log("Static constructor A");
}
}
public class B {
static B() {
Debug.Log("Static constructor B");
}
}
// Result: "Static constructor A"
That’s absolutely correct and you are getting the expected outcome. Static constructor B is never being called because you are never accessing class B from anywhere. The static constructor is not fired when the application starts, but it is when the first either static method is called or instance is created.