From Unify Community Wiki
Revision as of 17:07, 13 March 2011 by Statement (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The page says it's a singleton but it is not. "In computer engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object" It's quite possible to create several instances of AManager. <csharp>

  // instance1 and instance2 are two different instances and AManager is thus not a singleton.
  var instance1 = gameObject.AddComponent<AManager>();
  var instance2 = gameObject.AddComponent<AManager>();


In my own experiments with this class, I discovered that, when testing the game in the editor, s_Instance would tend to retain the instance used in the previous run of the game unless the script was recompiled. To avoid that, I used the Awake event to explicitly set the reference to the new object.

The problem with this trick is that it might mean that the instance reference isn't ready for other objects' Awake events if they get called before ours (they might get the previous game's object again). To avoid that, I've changed it to use OnApplicationQuit to set the current instance reference to null. This ensures that it will always be invalid the next time the game is run in the editor, which will cause a new object to be created. --NCarter 09:10, 19 February 2006 (EST)

Nice solution. I had actually dropped the whole property thing and had begun just doing the following: <csharp> public static MyClass instance; void Awake() {


} </csharp>

To avoid the problem you mentioned above, I have just used the fact that all Awake methods are called before calling any Start method, thus Awake sets up only internal stuff, and anything that references set up externally goes into Start. --Keli 22:49, 23 February 2006 (CET)

Personal tools