78 lines
2.5 KiB
C#
78 lines
2.5 KiB
C#
using System;
|
|
using Cysharp.Threading.Tasks;
|
|
using RebootKit.Engine.Services.Simulation;
|
|
using Unity.Collections;
|
|
using Unity.Netcode;
|
|
using UnityEngine;
|
|
using Logger = RebootKit.Engine.Foundation.Logger;
|
|
|
|
namespace RebootKit.Engine.Main {
|
|
public abstract class Game : NetworkBehaviour {
|
|
static readonly Logger s_GameLogger = new Logger(nameof(Game));
|
|
|
|
protected NetworkVariable<FixedString128Bytes> m_CurrentWorldID =
|
|
new NetworkVariable<FixedString128Bytes>(new FixedString128Bytes(""));
|
|
|
|
// Event callbacks
|
|
public virtual void OnWorldLoaded() {
|
|
}
|
|
|
|
public virtual void OnWorldUnload() {
|
|
}
|
|
|
|
public virtual void OnChatMessage(string message) {
|
|
s_GameLogger.Info($"Chat: {message}");
|
|
}
|
|
|
|
// Network
|
|
public override void OnNetworkSpawn() {
|
|
base.OnNetworkSpawn();
|
|
RR.GameInstance = this;
|
|
|
|
m_CurrentWorldID.OnValueChanged += OnCurrentWorldIDChanged;
|
|
LoadWorld(m_CurrentWorldID.Value.Value);
|
|
}
|
|
|
|
public override void OnNetworkDespawn() {
|
|
base.OnNetworkDespawn();
|
|
|
|
m_CurrentWorldID.OnValueChanged -= OnCurrentWorldIDChanged;
|
|
RR.GameInstance = null;
|
|
}
|
|
|
|
[ServerRpc]
|
|
public void SetCurrentWorldServerRpc(string worldID) {
|
|
m_CurrentWorldID.Value = new FixedString128Bytes(worldID);
|
|
}
|
|
|
|
// Chat
|
|
[Rpc(SendTo.Server)]
|
|
public void SendChatMessageRpc(string message) {
|
|
PrintChatMessageClientRpc(message);
|
|
}
|
|
|
|
[ClientRpc(Delivery = RpcDelivery.Reliable)]
|
|
void PrintChatMessageClientRpc(string message) {
|
|
OnChatMessage(message);
|
|
}
|
|
|
|
void OnCurrentWorldIDChanged(FixedString128Bytes previousValue, FixedString128Bytes newValue) {
|
|
string worldID = newValue.Value;
|
|
LoadWorld(worldID);
|
|
}
|
|
|
|
void LoadWorld(string worldID) {
|
|
if (string.IsNullOrEmpty(worldID)) {
|
|
RR.World.Unload();
|
|
} else {
|
|
WorldConfigAsset worldConfigAsset = RR.GetWorldConfigAsset(worldID);
|
|
if (worldConfigAsset is not null) {
|
|
RR.CloseMainMenu();
|
|
RR.World.LoadAsync(worldConfigAsset.Config, Application.exitCancellationToken).Forget();
|
|
} else {
|
|
s_GameLogger.Error($"World config asset for '{worldID}' not found.");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |