Tuesday, January 19, 2016

Lazy Initialization of Singleton in C# Unity

Singleton's are bad design patterns because they are essentially global variables or static classes vs individually static variables. Though we are taught to stay away from them in gaming they can come in handy, especially in Unity. I usually make my GameControllers singleton because there is essentially no chance that I'd need more than once instance of it.

Lazy initialization is nice because it'll initialize your instance when you need it, as you need it in the lifetime of your class.

As follows:

using UnityEngine;
using System.Collections;
using System;
using System.IO;
using Prime31;

public class GameController : Game {
public static GameController Instance { get; private set; }

#region Unity Behaviour
public void Awake () {
Instance = this;
        }
#endregion

}

You can design the class to inherit attributes (as mine does above from the Abstract Game Class). To reference the class from external classes you'd use GameController.Instance.*.  To access the internal variables when you use this Singleton you'll have to declare them as public.  In lieu of making public variables it's Ideally best to make them private and use getters and setters.

You can also pass Singleton's into methods and functions if you say for arguments sake have 2 classes inheriting from Game, both Singletons. You can decide which Singleton you want to pass in runtime, granted that both classes have the same method "someMethod()" in them publically. This can be done in runtime as follows:

     public void callMethod(Game p) {
         p.someMethod();
     }

    public void test() {
         callMethod(GameController.Instance);
    }

Though many argue Singleton is arguably an Anti-pattern, you can make the counter argument because of the usefulness and ubiquity of rampant use, it's legitimate in any programmer's arsenal.

No comments:

Post a Comment

Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...