MixedRealityToolkit-Unity icon indicating copy to clipboard operation
MixedRealityToolkit-Unity copied to clipboard

Singleton not guaranteed to exist if called from Awake

Open jamesashley1 opened this issue 9 years ago • 5 comments

The Singleton implementation uses eager instantiation, so it gets instantiated even if it doesn't actually get called -- that's just a c# purist problem. A more practical problem is that if it gets called from another Awake method, there's no guarantee it has been instantiated. You are rolling the dice.

This can be fixed by simply doing conditional (if null) instantiation in the Static Get method instead of in Awake.

jamesashley1 avatar Sep 28 '17 09:09 jamesashley1

Singleton has been a hot topic throughout the history of this repo, and, in fact, a version of it exists in our dev branch that works the way you describe: https://github.com/Microsoft/MixedRealityToolkit-Unity/blob/Dev_Unity_2017.2.0/Assets/HoloToolkit/Utilities/Scripts/SingleInstance.cs. This may be a good time to revisit our implementations.

keveleigh avatar Sep 29 '17 00:09 keveleigh

I would agree @keveleigh, since the current implementation doesn't really match what we are calling it at all...

jessemcculloch avatar Sep 29 '17 03:09 jessemcculloch

@keveleigh Definitely prefer this implementation.

@jamesashley1 I feel it makes sense to assume a MonoBehaviour-based Singleton will be present in the scene prior to being called, even if that's impure behavior. But it might help to name it 'MonoSingleton' or something.

A Singleton that extends ScriptableObject would probably be the best of both worlds - a pure singleton, serialized data and no instantiation headaches.

Railboy avatar Sep 29 '17 04:09 Railboy

A Singleton that extends ScriptableObject would probably be the best of both worlds - a pure singleton, serialized data and no instantiation headaches.

Definitely like this idea, but we would also want something that can also inherit from MonoBehavior as well.

StephenHodgson avatar Oct 02 '17 18:10 StephenHodgson

Fixed by #1160

StephenHodgson avatar Oct 14 '17 02:10 StephenHodgson