1
1
using System ;
2
+ using System . Collections ;
2
3
using System . Collections . Generic ;
3
4
using System . Linq ;
4
5
using Unity . Netcode ;
@@ -11,7 +12,7 @@ namespace Unity.Multiplayer.Samples.Utilities
11
12
/// <summary>
12
13
/// Custom spawning component to be added to a scene GameObject. This component collects NetworkObjects in a scene
13
14
/// marked by a special tag, collects their Transform data, destroys their prefab instance, and performs the dynamic
14
- /// spawning of said objects during Netcode for GameObject's OnNetworkSpawn() callback.
15
+ /// spawning of said objects during Netcode for GameObject's (Netcode) OnNetworkSpawn() callback.
15
16
/// </summary>
16
17
[ RequireComponent ( typeof ( NetcodeHooks ) ) ]
17
18
public class NetworkObjectSpawner : MonoBehaviour
@@ -27,7 +28,7 @@ public class NetworkObjectSpawner : MonoBehaviour
27
28
28
29
const string k_NetworkObjectSpawnerCollectableTag = "NetworkObjectSpawnerCollectable" ;
29
30
30
- void Start ( )
31
+ void Awake ( )
31
32
{
32
33
m_NetcodeHooks . OnNetworkSpawnHook += OnNetworkSpawn ;
33
34
}
@@ -48,6 +49,13 @@ void OnNetworkSpawn()
48
49
return ;
49
50
}
50
51
52
+ StartCoroutine ( WaitToSpawnNetworkObjects ( ) ) ;
53
+ }
54
+
55
+ IEnumerator WaitToSpawnNetworkObjects ( )
56
+ {
57
+ // must wait for Netcode's OnNetworkSpawn() sweep before dynamically spawning
58
+ yield return new WaitForEndOfFrame ( ) ;
51
59
SpawnNetworkObjects ( ) ;
52
60
}
53
61
@@ -57,7 +65,8 @@ void SpawnNetworkObjects()
57
65
{
58
66
var spawnedGameObject = Instantiate ( m_SpawnObjectData [ i ] . prefabReference ,
59
67
m_SpawnObjectData [ i ] . transform . position ,
60
- m_SpawnObjectData [ i ] . transform . rotation ) ;
68
+ m_SpawnObjectData [ i ] . transform . rotation ,
69
+ null ) ;
61
70
62
71
spawnedGameObject . transform . localScale = m_SpawnObjectData [ i ] . transform . lossyScale ;
63
72
var spawnedNetworkObject = spawnedGameObject . GetComponent < NetworkObject > ( ) ;
@@ -68,8 +77,7 @@ void SpawnNetworkObjects()
68
77
}
69
78
70
79
#if UNITY_EDITOR
71
- [ ContextMenu ( "Collect" ) ]
72
- public void Collect ( )
80
+ public void CollectTaggedPrefabInstances ( )
73
81
{
74
82
var prefabStage = PrefabStageUtility . GetPrefabStage ( gameObject ) ;
75
83
@@ -121,7 +129,7 @@ public override void OnInspectorGUI()
121
129
if ( PrefabStageUtility . GetCurrentPrefabStage ( ) &&
122
130
GUILayout . Button ( "Collect tagged prefab instances" ) )
123
131
{
124
- networkObjectSpawner . Collect ( ) ;
132
+ networkObjectSpawner . CollectTaggedPrefabInstances ( ) ;
125
133
}
126
134
}
127
135
}
0 commit comments