- Home /
javascript singleton
hi! i am trying to implement singleton class but i am totally confused.
i made a class that i want to use in my project it goes something like this (this is the simplified version):
class EControl{
var state : boolean;
//constructor
function EControl(){
state=false;
}
function getState() : boolean{
return state;
}
}
so i later on i realized that i need to have to access object of this class in more then one script and has to be the same object so the value that is set is the same. i was looking what is available in the forums and i found two resources. this one i dont understand http://www.unifycommunity.com/wiki/index.php?title=AManagerClass and this one is not working (i get "there is no instance") http://forum.unity3d.com/viewtopic.php?p=388784#388784
so i would appreciate if someone could explain how to make this work and how to use one object of this class in two separate scripts.
thank you!
Answer by SteveFSP · Sep 02, 2010 at 04:57 PM
Here is a simple example with comments:
class EControl {
// This is the singleton instance that is shared with everyone.
private static var Instance : EControl;
// Everything that needs to get the singleton
// instance, calls this function to get it.
public static function GetInstance() : EControl
{
if (Instance == null)
// This is the first time the function was called. Need to
// construct the shared instance.
Instance = new EControl();
return Instance;
}
var state : boolean ;
// Private constructor. This is what forces the class
// to be a singleton since the only way to construct it
// is via GetInstance().
// NOTE: Private constructors are not normally allowed
// in JavaScript. But it is OK in Unity.
private function EControl()
{
state=false;
}
function GetState() : boolean
{
return state;
}
}
You get instances of the singleton as follows:
private var control : EControl;
function Start() { control = EControl.GetInstance(); Debug.Log(control.GetState()); // The next line would cause a compile time error due to // the constructor's protection level. // control = new EControl(); }
Still wish I understood the importance of Classes! (Yes, I'm a noob and trying to get my head around them)!