-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathNetworkSingleton.cs
More file actions
53 lines (43 loc) · 1.31 KB
/
NetworkSingleton.cs
File metadata and controls
53 lines (43 loc) · 1.31 KB
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
51
52
53
// Copyright (c) Meta Platforms, Inc. and affiliates.
using Unity.Netcode;
using UnityEngine;
namespace Meta.Multiplayer.Networking
{
public class NetworkSingleton<T> : NetworkBehaviour where T : NetworkSingleton<T>
{
public static T Instance { get; private set; }
private static System.Action<T> s_onAwake;
private static System.Action<T> s_onDestroy;
public static void WhenInstantiated(System.Action<T> action)
{
if (Instance != null)
action(Instance);
else
s_onAwake += action;
}
public static void WhenDestroyed(System.Action<T> action)
{
s_onDestroy += action;
}
protected void Awake()
{
if (!enabled)
return;
Debug.Assert(Instance == null, $"Singleton {typeof(T).Name} has been instantiated more than once.", this);
Instance = (T)this;
s_onAwake?.Invoke(Instance);
s_onAwake = null;
}
protected void OnEnable()
{
if (Instance != this)
Awake();
}
public override void OnDestroy()
{
s_onDestroy?.Invoke(Instance);
s_onDestroy = null;
base.OnDestroy();
}
}
}