-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkObjectSpawner.cs
50 lines (45 loc) · 1.72 KB
/
NetworkObjectSpawner.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Unity.Multiplayer.Samples.Utilities
{
public class NetworkObjectSpawner : MonoBehaviour
{
public NetworkObject prefabReference;
public void Awake()
{
if (NetworkManager.Singleton && NetworkManager.Singleton.IsServer &&
NetworkManager.Singleton.SceneManager != null)
{
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += SceneManagerOnOnLoadEventCompleted;
}
else
{
Destroy(gameObject);
}
}
void OnDestroy()
{
if (NetworkManager.Singleton && NetworkManager.Singleton.IsServer &&
NetworkManager.Singleton.SceneManager != null)
{
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted -= SceneManagerOnOnLoadEventCompleted;
}
}
void SceneManagerOnOnLoadEventCompleted(string sceneName, LoadSceneMode loadSceneMode, List<ulong> clientsCompleted, List<ulong> clientsTimedOut)
{
SpawnNetworkObject();
Destroy(gameObject);
}
void SpawnNetworkObject()
{
var instantiatedNetworkObject = Instantiate(prefabReference, transform.position, transform.rotation, null);
SceneManager.MoveGameObjectToScene(instantiatedNetworkObject.gameObject,
SceneManager.GetSceneByName(gameObject.scene.name));
instantiatedNetworkObject.transform.localScale = transform.lossyScale;
instantiatedNetworkObject.Spawn(destroyWithScene: true);
}
}
}