Skip to content

Commit 6080134

Browse files
committed
Added a solution based on inheritance
Inheriting from this abstract class insteead of a NetworkBehaviour allows a script to be disabled on Awake and only enabled in a client or a server specifically
1 parent 97c5e2b commit 6080134

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using System;
2+
using Unity.Netcode;
3+
using UnityEngine;
4+
5+
/// <summary>
6+
/// NetworkBehaviour that is only enabled when spawned, on either the server or a client.
7+
/// </summary>
8+
public abstract class RoleRestrictedNetworkBehaviour : NetworkBehaviour
9+
{
10+
/// <summary>
11+
/// Returns the role for which this NetworkBehaviour should be enabled.
12+
/// </summary>
13+
/// <returns></returns>
14+
protected abstract Role GetTargetRole();
15+
16+
protected enum Role
17+
{
18+
Client,
19+
Server
20+
}
21+
22+
void Awake()
23+
{
24+
// Disable this NetworkBehaviour until it is spawned
25+
enabled = false;
26+
}
27+
28+
public override void OnNetworkSpawn()
29+
{
30+
// enable this NetworkBehaviour only for the target role
31+
switch (GetTargetRole())
32+
{
33+
case Role.Client:
34+
enabled = IsClient;
35+
break;
36+
case Role.Server:
37+
enabled = IsServer;
38+
break;
39+
}
40+
}
41+
42+
public override void OnNetworkDespawn()
43+
{
44+
// Disable This NetworkBehaviour again, until it is either destroyed or spawned again
45+
enabled = false;
46+
}
47+
}

Assets/BossRoom/Scripts/Shared/RoleRestrictedNetworkBehaviour.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)