1
+ #if ! DEDICATED_SERVER || ( DEDICATED_SERVER && ! UNITY_EDITOR )
1
2
using System ;
3
+ #endif
2
4
using System . Collections . Generic ;
3
5
using System . Linq ;
6
+ #if ! DEDICATED_SERVER
4
7
using System . Threading . Tasks ;
8
+ #endif
5
9
using Unity . Netcode ;
10
+ #if ! DEDICATED_SERVER
6
11
using Unity . Services . Authentication ;
7
12
using Unity . Services . Core ;
8
13
using Unity . Services . Multiplayer ;
14
+ #else
15
+ using Unity . Netcode . Transports . UTP ;
16
+ #endif
9
17
using UnityEngine ;
18
+ #if ! DEDICATED_SERVER
10
19
using SessionState = Unity . Services . Multiplayer . SessionState ;
20
+ #endif
11
21
12
22
#region NetworkManagerBootstrapperEditor
13
23
#if UNITY_EDITOR
@@ -67,7 +77,7 @@ protected override void OnValidateComponent()
67
77
base . OnValidateComponent ( ) ;
68
78
}
69
79
#endif
70
- #endregion
80
+ #endregion
71
81
72
82
#region Properties
73
83
public static NetworkManagerBootstrapper Instance ;
@@ -98,12 +108,13 @@ private enum ConnectionStates
98
108
99
109
[ SerializeField ]
100
110
private bool m_ServicesRegistered ;
111
+ #if ! DEDICATED_SERVER
101
112
private ISession m_CurrentSession ;
102
113
private string m_SessionName ;
103
114
private string m_ProfileName ;
104
115
private Task m_SessionTask ;
105
-
106
- #endregion
116
+ #endif
117
+ #endregion
107
118
108
119
#region Initialization and Destroy
109
120
public static string GetRandomString ( int length )
@@ -120,12 +131,27 @@ public void SetFrameRate(int targetFrameRate, bool enableVsync)
120
131
121
132
private void Awake ( )
122
133
{
134
+ #if ! DEDICATED_SERVER
123
135
Screen . SetResolution ( ( int ) ( Screen . currentResolution . width * 0.40f ) , ( int ) ( Screen . currentResolution . height * 0.40f ) , FullScreenMode . Windowed ) ;
124
136
SetFrameRate ( TargetFrameRate , EnableVSync ) ;
137
+ #endif
125
138
SetSingleton ( ) ;
126
139
m_SceneBootstrapLoader = GetComponent < SceneBootstrapLoader > ( ) ;
127
140
}
128
141
142
+ #if DEDICATED_SERVER
143
+ private void Start ( )
144
+ {
145
+ m_SceneBootstrapLoader . OnMainMenuLoaded += OnMainMenuLoaded ;
146
+ m_SceneBootstrapLoader . LoadMainMenu ( ) ;
147
+ }
148
+
149
+ private void OnMainMenuLoaded ( )
150
+ {
151
+ m_SceneBootstrapLoader . OnMainMenuLoaded -= OnMainMenuLoaded ;
152
+ StartDedicatedServer ( ) ;
153
+ }
154
+ #else
129
155
private async void Start ( )
130
156
{
131
157
OnClientConnectedCallback += OnClientConnected ;
@@ -152,17 +178,20 @@ private async void Start()
152
178
}
153
179
}
154
180
m_SceneBootstrapLoader . LoadMainMenu ( ) ;
155
- }
156
181
182
+ }
157
183
private void OnDestroy ( )
158
184
{
159
185
OnClientConnectedCallback -= OnClientConnected ;
160
186
OnClientDisconnectCallback -= OnClientDisconnect ;
161
187
OnConnectionEvent -= OnClientConnectionEvent ;
162
188
}
163
- #endregion
189
+ #endif
190
+ #endregion
164
191
165
192
#region Session and Connection Event Handling
193
+
194
+ #if ! DEDICATED_SERVER
166
195
private void OnClientConnectionEvent ( NetworkManager networkManager , ConnectionEventData eventData )
167
196
{
168
197
LogMessage ( $ "[{ Time . realtimeSinceStartup } ] Connection event { eventData . EventType } for Client-{ eventData . ClientId } .") ;
@@ -235,9 +264,11 @@ private async Task<ISession> ConnectThroughLiveService()
235
264
}
236
265
return null ;
237
266
}
238
- #endregion
267
+ #endif
268
+ #endregion
239
269
240
270
#region GUI Menu
271
+ #if ! DEDICATED_SERVER
241
272
public void StartOrConnectToDistributedAuthoritySession ( )
242
273
{
243
274
m_SessionTask = ConnectThroughLiveService ( ) ;
@@ -364,9 +395,11 @@ private void OnGUI()
364
395
}
365
396
GUILayout . EndArea ( ) ;
366
397
}
367
- #endregion
398
+ #endif
399
+ #endregion
368
400
369
401
#region Server Camera Handling
402
+ #if ! DEDICATED_SERVER
370
403
private Vector3 m_CameraOriginalPosition ;
371
404
private Quaternion m_CameraOriginalRotation ;
372
405
private int m_CurrentFollowPlayerIndex = - 1 ;
@@ -438,9 +471,159 @@ public void ClearFollowPlayer()
438
471
SetCameraDefaults ( ) ;
439
472
}
440
473
}
441
- #endregion
474
+ #endif
475
+ #endregion
442
476
443
477
#region Update Methods and Properties
478
+ #if DEDICATED_SERVER
479
+ private UnityTransport m_UnityTransport ;
480
+ /// <summary>
481
+ /// All of the dedicated server specific script logic is contained and only compiled when DEDICATED_SERVER is defined
482
+ /// </summary>
483
+
484
+ private void StartDedicatedServer ( )
485
+ {
486
+ m_UnityTransport = NetworkConfig . NetworkTransport as UnityTransport ;
487
+ if ( m_UnityTransport != null )
488
+ {
489
+ // Always good to know what scenes are currently loaded since you might have
490
+ // different scenes to load for a DGS vs client
491
+ var scenesPreloaded = new System . Text . StringBuilder ( ) ;
492
+ scenesPreloaded . Append ( "Scenes Preloaded: " ) ;
493
+ for ( int i = 0 ; i < UnityEngine . SceneManagement . SceneManager . sceneCount ; i ++ )
494
+ {
495
+ var scene = UnityEngine . SceneManagement . SceneManager . GetSceneAt ( i ) ;
496
+ scenesPreloaded . Append ( $ "[{ scene . name } ]") ;
497
+ }
498
+ Debug . Log ( scenesPreloaded . ToString ( ) ) ;
499
+
500
+ // Set the application frame rate to like 30 to reduce frame processing overhead
501
+ Application . targetFrameRate = 30 ;
502
+
503
+ Debug . Log ( $ "[Pre-Init] Server Address Endpoint: { m_UnityTransport . ConnectionData . ServerEndPoint } ") ;
504
+ Debug . Log ( $ "[Pre-Init] Server Listen Endpoint: { m_UnityTransport . ConnectionData . ListenEndPoint } ") ;
505
+ // Setup your IP and port sepcific to your DGS
506
+ //unityTransport.SetConnectionData(ListenAddress, ListenPort, ListenAddress);
507
+
508
+ //Debug.Log($"[Post-Init] Server Address Endpoint: {unityTransport.ConnectionData.ServerEndPoint}");
509
+ //Debug.Log($"[Post-Init] Server Listen Endpoint: {unityTransport.ConnectionData.ListenEndPoint}");
510
+
511
+ // Get the server started notification
512
+ OnServerStarted += ServerStarted ;
513
+
514
+ // Start the server listening
515
+ m_SceneBootstrapLoader . StartSession ( SceneBootstrapLoader . StartAsTypes . Server ) ;
516
+ }
517
+ else
518
+ {
519
+ Debug . LogError ( "Failed to get the UnityTransport!" ) ;
520
+ }
521
+ }
522
+
523
+ /// <summary>
524
+ /// Register callbacks when the OnServerStarted callback is invoked.
525
+ /// This makes it easier to know you are registering for events only
526
+ /// when the server successfully has started.
527
+ /// </summary>
528
+ private void ServerStarted ( )
529
+ {
530
+ Debug . Log ( "Dedicated Server Started!" ) ;
531
+ Debug . Log ( $ "[Started] Server Address Endpoint: { m_UnityTransport . ConnectionData . ServerEndPoint } ") ;
532
+ Debug . Log ( $ "[Started] Server Listen Endpoint: { m_UnityTransport . ConnectionData . ListenEndPoint } ") ;
533
+ Debug . Log ( "===============================================================" ) ;
534
+ Debug . Log ( "[X] Exits session (Shutdown) | [ESC] Exits application instance" ) ;
535
+ Debug . Log ( "===============================================================" ) ;
536
+ OnServerStarted -= ServerStarted ;
537
+ OnClientConnectedCallback += ClientConnectedCallback ;
538
+ OnClientDisconnectCallback += ClientDisconnectCallback ;
539
+ // Register for OnServerStopped
540
+ OnServerStopped += ServerStopped ;
541
+ }
542
+
543
+ private void ServerStopped ( bool obj )
544
+ {
545
+ OnClientConnectedCallback -= ClientConnectedCallback ;
546
+ OnClientDisconnectCallback -= ClientDisconnectCallback ;
547
+ OnServerStopped -= ServerStopped ;
548
+ Debug . Log ( "Dedicated Server Stopped!" ) ;
549
+ Debug . Log ( "===============================================================" ) ;
550
+ Debug . Log ( "[S] Starts new session (StartServer) | [ESC] Exits application" ) ;
551
+ Debug . Log ( "===============================================================" ) ;
552
+ }
553
+
554
+ private void ClientConnectedCallback ( ulong clientId )
555
+ {
556
+ Debug . Log ( $ "Client-{ clientId } connected and approved.") ;
557
+ }
558
+
559
+ private void ClientDisconnectCallback ( ulong clientId )
560
+ {
561
+ Debug . Log ( $ "Client-{ clientId } disconnected.") ;
562
+ }
563
+
564
+ #if UNITY_EDITOR
565
+ private void HandleEditorKeyCommands ( )
566
+ {
567
+ // Shutdown/Stop the server
568
+ if ( Input . GetKeyDown ( KeyCode . X ) && IsListening && ! ShutdownInProgress )
569
+ {
570
+ Shutdown ( ) ;
571
+ }
572
+ else // Start the server (this example makes it automatically start when the application first starts)
573
+ if ( Input . GetKeyDown ( KeyCode . S ) && ! IsListening )
574
+ {
575
+ StartDedicatedServer ( ) ;
576
+ }
577
+ }
578
+ #else
579
+ private void HandleConsoleKeyCommands ( )
580
+ {
581
+ if ( Console . KeyAvailable )
582
+ {
583
+ var networkManager = NetworkManager . Singleton ;
584
+ var keyPressed = Console . ReadKey ( true ) ;
585
+ switch ( keyPressed . Key )
586
+ {
587
+ case ConsoleKey . X :
588
+ {
589
+ if ( networkManager . IsListening && ! networkManager . ShutdownInProgress )
590
+ {
591
+ networkManager . Shutdown ( ) ;
592
+ }
593
+ break ;
594
+ }
595
+ case ConsoleKey . S :
596
+ {
597
+ if ( ! networkManager . IsListening && ! networkManager . ShutdownInProgress )
598
+ {
599
+ StartDedicatedServer ( ) ;
600
+ }
601
+ break ;
602
+ }
603
+ case ConsoleKey . Escape :
604
+ {
605
+ Application . Quit ( ) ;
606
+ break ;
607
+ }
608
+ }
609
+ }
610
+ }
611
+ #endif
612
+
613
+ /// <summary>
614
+ /// Update that is only included in the build and invoked when running as a dedicated server
615
+ /// </summary>
616
+ private void DedicatedServerUpdate ( )
617
+ {
618
+ #if UNITY_EDITOR
619
+ HandleEditorKeyCommands ( ) ;
620
+ #else
621
+ HandleConsoleKeyCommands ( ) ;
622
+ #endif
623
+ }
624
+
625
+ #else // End of DEDICATED_SERVER defined region
626
+
444
627
/// <summary>
445
628
/// General update for server-side
446
629
/// </summary>
@@ -459,9 +642,13 @@ private void ClientSideUpdate()
459
642
{
460
643
461
644
}
645
+ #endif
462
646
463
647
private void Update ( )
464
648
{
649
+ #if DEDICATED_SERVER
650
+ DedicatedServerUpdate ( ) ;
651
+ #else
465
652
if ( IsListening )
466
653
{
467
654
if ( IsServer )
@@ -473,6 +660,7 @@ private void Update()
473
660
ClientSideUpdate ( ) ;
474
661
}
475
662
}
663
+ #endif
476
664
477
665
if ( m_MessageLogs . Count == 0 )
478
666
{
@@ -487,6 +675,7 @@ private void Update()
487
675
}
488
676
}
489
677
}
678
+
490
679
#endregion
491
680
492
681
#region Message Logging
0 commit comments