Engine-Pong/Game/Network/NetworkBehaviour.cs

53 lines
1.5 KiB
C#

using System;
using Syntriax.Engine.Core;
using Syntriax.Engine.Network.Abstract;
namespace Syntriax.Engine.Network;
public abstract class NetworkBehaviour : BehaviourOverride, INetworkBehaviour
{
public event INetworkEntity.OnNetworkIdChangedDelegate? OnNetworkIdChanged = null;
private uint _networkId = 0;
public uint NetworkId
{
get => _networkId;
set
{
if (value == _networkId)
return;
uint previousNetworkId = _networkId;
_networkId = value;
OnNetworkIdChanged?.Invoke(this, previousNetworkId);
}
}
public bool IsServer { get; private set; } = false;
public bool IsClient { get; private set; } = false;
public INetworkCommunicator NetworkCommunicator { get; private set; } = null!;
protected override void OnInitialize()
{
NetworkCommunicator = BehaviourController.GetBehaviourInParent<INetworkCommunicator>()
?? GameObject.GameManager.FindBehaviour<INetworkCommunicator>()
?? throw new Exception($"Could not find an {nameof(INetworkCommunicator)}.");
if (NetworkCommunicator is INetworkCommunicatorClient client)
{
IsClient = true;
return;
}
IsServer = true;
}
public void SendData<T>(T data)
=> NetworkCommunicator.Send(new NetworkPacket<T>() { NetworkId = _networkId, Data = data });
public abstract void ReceiveData<T>(T data);
}