Hi,
DoNotDestroyOnLoad used to keep the GO for next level, that’s good and work well no problem at all. But I’m facing problem like this:
I have a GO named “game_controller” and in this GO has an JS scripted component where I defined it in the Awake function as DoNotDestroyOnLoad(). So, this GO is not destroying across the game. I defined it in the Main_Menu scene. So, when I’m entering in to game and come back to Main Menu again by Application.LoadLevel(“Main_Menu”) then I’m getting another instance of “game_controller” and this is Unity should do. My question is, how can I prevent it?
I have an solution like making this GO into another scene like splash which will never get call. But is there any better idea rather than this?
This is not really iPhone related - more related to scripting in general. What I use for this kind of thing is something like the following code (this is C# but should be easy to convert to UnityScript in case you need that):
#region Unity Singleton Pattern
private static <YourClassName> instance = null;
/// <summary>
/// Gets the singleton instance of the <YourClassName>.
/// </summary>
public static <YourClassName> Instance {
get { return instance; }
}
/// <summary>
/// Initializes the <YourClassName>
/// singleton instance or destroys
/// obsolete instances.
/// </summary>
void Awake() {
if (instance != null instance != this) {
Destroy(this.gameObject);
return;
} else {
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
#endregion Unity Singleton Pattern
IIRC, this is from Workflow and Asset Pipeline (I may have modified it somewhat to suit my needs, but I think it’s actually exactly the way it was introduced there).
UML tools might include Singletons or other patterns but I really don’t see what use would be including “out-of-the-box” design patterns in a game engine (in the sense that Unity would “have” singletons). Okay - when dealing with game objects you can’t use “the pure Singleton pattern”, but it’s “close enough”