- Home /
Is there a known issue where singletons will run constructors multiple times?
I am seeing some strange behavior in a class I am working with. It is a singleton that looks like this:
class GameState {
static private var gameState : GameState = null;
static function Instance () : GameState {
if ( gameState == null ) {
Debug.Log( 'test1' );
gameState = new GameState();
}
return gameState;
}
function GameState () {
Debug.Log( 'test2' );
// do other stuff here
}
}
There's more, but I have cut it down to the necessary pieces. When I run GameState.Instance()
, here is what prints:
test2
test2
test1
test2
So it appears what is happening is that the constructor is running twice before I ever even call new GameState()
. Why would this occur??
I have ruled out other parts of the code calling new GameState()
by doing a thorough search of the entire project's files. I'm at a loss as to why this would happen.
There are a couple of other classes contained within this same file. The file is named GameState. I am not sure if this is relevant to the issue.
I just copy/pasted the code above into a new UnityScript, then made another one with nothing but :
function Start()
{
GameState.Instance() ;
}
... attached script 2 to three objects in the scene. Pressed play. Result.
test1
test2
Then added script 2 to one of those objects 4 times, and another one of them 3 times. Pressed play. Same Debug result.
Edit : ...Named the file GameState also just now, at first it was named something else. Same debug result, tho.
I guess I should have tried that. Very interesting. It makes me think this has something to do with the other classes contained within the same file.
Even though the other classes have different names, if they are contained within a file named after the first class, maybe is causing something weird.
Your answer
Follow this Question
Related Questions
Saving last checkpoint hit when reloading scene - Singletons? 1 Answer
singleton, static var, local reference. Whats better? 1 Answer
Create a persistent GameObject using Singleton 3 Answers
Text UI erases after new scene. 1 Answer
Class that extends another class that extends Singleton generic class 1 Answer