quantum-space-buddies/QSB/Utility/QSBNetworkBehaviour.cs

80 lines
1.8 KiB
C#
Raw Normal View History

2022-01-14 20:13:04 -08:00
using Mirror;
using System;
namespace QSB.Utility
{
public abstract class QSBNetworkBehaviour : NetworkBehaviour
{
protected virtual float SendInterval => 0.1f;
2022-01-14 21:25:02 -08:00
protected virtual bool UseReliableRpc => false;
2022-01-14 20:13:04 -08:00
private double _lastSendTime;
protected abstract bool HasChanged();
protected abstract void UpdatePrevData();
protected abstract void Serialize(NetworkWriter writer);
protected abstract void Deserialize(NetworkReader reader);
2022-01-14 20:13:04 -08:00
protected virtual void Update()
{
if (!isClient)
{
return;
}
if (!hasAuthority)
{
return;
}
if (!NetworkClient.ready)
{
return;
}
if (NetworkTime.localTime >= _lastSendTime + SendInterval)
{
_lastSendTime = NetworkTime.localTime;
if (!HasChanged())
{
return;
}
using var writer = NetworkWriterPool.GetWriter();
Serialize(writer);
2022-01-16 00:15:27 -08:00
UpdatePrevData();
2022-01-14 20:13:04 -08:00
var data = writer.ToArraySegment();
2022-01-14 21:25:02 -08:00
if (UseReliableRpc)
2022-01-14 20:13:04 -08:00
{
2022-01-14 21:25:02 -08:00
CmdSendDataReliable(data);
2022-01-14 20:13:04 -08:00
}
else
{
2022-01-14 21:25:02 -08:00
CmdSendDataUnreliable(data);
2022-01-14 20:13:04 -08:00
}
}
}
[Command(channel = Channels.Reliable, requiresAuthority = true)]
private void CmdSendDataReliable(ArraySegment<byte> data) => RpcSendDataReliable(data);
[ClientRpc(channel = Channels.Reliable, includeOwner = false)]
private void RpcSendDataReliable(ArraySegment<byte> data) => OnData(data);
2022-01-14 21:25:02 -08:00
[Command(channel = Channels.Unreliable, requiresAuthority = true)]
private void CmdSendDataUnreliable(ArraySegment<byte> data) => RpcSendDataUnreliable(data);
[ClientRpc(channel = Channels.Unreliable, includeOwner = false)]
private void RpcSendDataUnreliable(ArraySegment<byte> data) => OnData(data);
2022-01-14 20:13:04 -08:00
private void OnData(ArraySegment<byte> data)
{
using var reader = NetworkReaderPool.GetReader(data);
2022-01-16 00:15:27 -08:00
UpdatePrevData();
Deserialize(reader);
2022-01-14 20:13:04 -08:00
}
}
}