refactor
This commit is contained in:
@@ -1,47 +1,57 @@
|
||||
using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using R3;
|
||||
using RebootKit.Engine.Foundation;
|
||||
using UnityEngine.Assertions;
|
||||
|
||||
namespace RebootKit.Engine.Services.Game {
|
||||
public class GameService : IService {
|
||||
static readonly Logger s_logger = new(nameof(GameService));
|
||||
|
||||
[Inject] DIContext m_DIContext;
|
||||
GameMode m_GameMode;
|
||||
|
||||
GameModeAsset m_GameModeAsset;
|
||||
bool m_isRunning;
|
||||
|
||||
CancellationTokenSource m_DestroyCancellationTokenSource = new();
|
||||
DisposableBag m_ActiveGameModeDisposableBag;
|
||||
IGameMode m_ActiveGameMode;
|
||||
|
||||
public void Dispose() {
|
||||
m_isRunning = false;
|
||||
m_GameMode.Dispose();
|
||||
m_DestroyCancellationTokenSource.Cancel();
|
||||
m_DestroyCancellationTokenSource.Dispose();
|
||||
m_ActiveGameModeDisposableBag.Dispose();
|
||||
}
|
||||
|
||||
public async UniTask Start(GameModeAsset asset, CancellationToken cancellationToken) {
|
||||
Assert.IsNotNull(asset);
|
||||
|
||||
m_GameMode = asset.Create(m_DIContext);
|
||||
await m_GameMode.Start(cancellationToken);
|
||||
|
||||
Run(cancellationToken).Forget();
|
||||
}
|
||||
|
||||
async UniTask Run(CancellationToken cancellationToken) {
|
||||
if (m_GameMode == null) {
|
||||
s_logger.Error("Trying to run game without game mode");
|
||||
public void Start(GameModeAsset asset) {
|
||||
if (m_ActiveGameMode != null) {
|
||||
s_logger.Warning("Game is already running");
|
||||
return;
|
||||
}
|
||||
|
||||
m_isRunning = true;
|
||||
while (m_isRunning) {
|
||||
await UniTask.Yield(PlayerLoopTiming.Update, cancellationToken);
|
||||
m_GameMode.Tick();
|
||||
Stop();
|
||||
|
||||
if (cancellationToken.IsCancellationRequested) {
|
||||
return;
|
||||
}
|
||||
m_ActiveGameModeDisposableBag = new DisposableBag();
|
||||
m_ActiveGameMode = asset.Create(m_DIContext);
|
||||
m_ActiveGameModeDisposableBag.Add(m_ActiveGameMode);
|
||||
|
||||
InitializeGameModeAsync().Forget();
|
||||
}
|
||||
|
||||
async UniTask InitializeGameModeAsync() {
|
||||
await m_ActiveGameMode.OnInit(m_DestroyCancellationTokenSource.Token);
|
||||
|
||||
m_ActiveGameMode.OnStart();
|
||||
Observable.EveryUpdate().Subscribe(_ => { m_ActiveGameMode?.OnTick(); }).AddTo(ref m_ActiveGameModeDisposableBag);
|
||||
}
|
||||
|
||||
public void Stop() {
|
||||
if (m_ActiveGameMode == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_ActiveGameMode.OnStop();
|
||||
m_ActiveGameMode = null;
|
||||
|
||||
m_ActiveGameModeDisposableBag.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user