Hey Guys,
I’m just getting my head around the idea of using singletons to access static variables/functions etc. I got this declaration code from an official Unity tutorial and have modified it to work with my scripts. I’m just using it so that I can access an instance from other scripts. This code worked:
private static SettingsManager settingsManager;
public static SettingsManager Instance () {
if (!settingsManager) {
settingsManager = FindObjectOfType(typeof (SettingsManager)) as SettingsManager;
if (!settingsManager)
Debug.LogError ("There needs to be one active Settings Manager script on a GameObject in your scene.");
}
return settingsManager;
}
As soon as I made another script that can be accessed this way, the console hated it. This throws about 8 errors:
private static ToolManager toolManager;
public static ToolManager Instance () {
if (!toolManager) {
toolManager = FindObjectOfType(typeof (ToolManager)) as ToolManager;
if (!toolManager)
Debug.LogError ("There needs to be one active Tool Manager script on a GameObject in your scene.");
}
return toolManager;
}
The errors are as follows:
UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don’t use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
and
FindObjectsOfType can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
SO… tl;dr essentially the same code, but one throws errors. The other weird thing is that my game runs, and the scripts all work as I’d expect, but my console is flooded with multiple copies of the same two errors. I’ve tried deleting the script and re creating it as someone suggested that it might be corrupted, didn’t work.
Any ideas? Thanks so much in advance!