11using __TEMPLATE__ . Debugging ;
22using __TEMPLATE__ . UI ;
33using __TEMPLATE__ . UI . Console ;
4+ using System ;
45
56namespace __TEMPLATE__ ;
67
78public static class Game
89{
10+ #if DEBUG
11+ /// <summary>
12+ /// Check if the autoloads singleton is not null. If it is null then show an error explaining
13+ /// that the developer cannot access the autoloads singleton just yet and it needs time to
14+ /// setup.
15+ /// </summary>
16+ private static T IsAutoloadsSetup < T > ( Func < Autoloads , T > getPropertyFrom , string propertyName ) where T : class
17+ {
18+ Autoloads autoloads = Autoloads . Instance ;
19+
20+ if ( autoloads == null )
21+ {
22+ string errMsg = $ "Game.{ propertyName } was accessed before _EnterTree or _Ready.";
23+
24+ #if NETCODE_ENABLED
25+ // Show a friendly optional error message if netcode is enabled.
26+ // Since Autoloads is null we can make our own temporary Logger.
27+ Logger logger = new ( ) ;
28+ logger . LogDebug ( errMsg + " (see exception in errors for stack trace)" ) ;
29+ logger . Update ( ) ;
30+ #endif
31+ throw new InvalidOperationException ( errMsg ) ;
32+ }
33+
34+ return getPropertyFrom ( autoloads ) ! ; // Assumes the field may be null, but we are not checking it here
35+ }
36+
37+ public static MetricsOverlay Metrics => IsAutoloadsSetup ( a => a . MetricsOverlay , nameof ( Metrics ) ) ;
38+ public static OptionsManager Options => IsAutoloadsSetup ( a => a . OptionsManager , nameof ( Options ) ) ;
39+ public static AudioManager Audio => IsAutoloadsSetup ( a => a . AudioManager , nameof ( Audio ) ) ;
40+ public static SceneManager Scene => IsAutoloadsSetup ( a => a . SceneManager , nameof ( Scene ) ) ;
41+ public static GameConsole Console => IsAutoloadsSetup ( a => a . GameConsole , nameof ( Console ) ) ;
42+ public static Profiler Profiler => IsAutoloadsSetup ( a => a . Profiler , nameof ( Profiler ) ) ;
43+ public static Services Services => IsAutoloadsSetup ( a => a . Services , nameof ( Services ) ) ;
44+ public static Logger Logger => IsAutoloadsSetup ( a => a . Logger , nameof ( Logger ) ) ;
45+ #else
46+ // The games release will not have the slow debugging checks
947 public static MetricsOverlay Metrics => Autoloads . Instance . MetricsOverlay ;
1048 public static OptionsManager Options => Autoloads . Instance . OptionsManager ;
1149 public static AudioManager Audio => Autoloads . Instance . AudioManager ;
@@ -14,4 +52,5 @@ public static class Game
1452 public static Profiler Profiler => Autoloads . Instance . Profiler ;
1553 public static Services Services => Autoloads . Instance . Services ;
1654 public static Logger Logger => Autoloads . Instance . Logger ;
17- }
55+ #endif
56+ }
0 commit comments