update sample

This commit is contained in:
hevinci
2022-11-25 21:40:54 +08:00
parent 82cff36194
commit 5718d57b88
223 changed files with 5950 additions and 2216 deletions
@@ -1,15 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BattleEventDefine
{
public class ScoreChange : IEventMessage
{
public int CurrentScores;
}
public class GameOver : IEventMessage
{
}
}
@@ -1,19 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class BattleEventDispatcher
{
public static void SendScoreChangeMsg(int currentScores)
{
BattleEventDefine.ScoreChange msg = new BattleEventDefine.ScoreChange();
msg.CurrentScores = currentScores;
EventManager.SendMessage(msg);
}
public static void SendGameOverMsg()
{
BattleEventDefine.GameOver msg = new BattleEventDefine.GameOver();
EventManager.SendMessage(msg);
}
}
@@ -1,110 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using YooAsset;
using Random = UnityEngine.Random;
[Serializable]
public class RoomBoundary
{
public float xMin, xMax, zMin, zMax;
}
public class BattleRoom : MonoBehaviour
{
public static BattleRoom Instance;
public Vector3 SpawnValues;
public int EnemyCount = 10;
public float SpawnWait = 0.75f;
public float StartWait = 1f;
public float WaveWait = 4f;
private int _totalScore = 0;
private bool _gameOver = false;
private string[] _enemyLocations = new string[]
{
"asteroid01", "asteroid02", "asteroid03", "enemy_ship"
};
private AssetOperationHandle _panelHandle;
void Awake()
{
Instance = this;
var canvas = GameObject.Find("Canvas");
_panelHandle = YooAssets.LoadAssetSync<GameObject>("UIBattle");
var go = _panelHandle.InstantiateSync(canvas.transform);
go.transform.localPosition = Vector3.zero;
}
void Start()
{
var handle = YooAssets.LoadAssetSync<GameObject>("player_ship");
var go = handle.InstantiateSync();
var bhv = go.GetComponent<EntityPlayer>();
bhv.InitEntity(handle);
StartCoroutine(SpawnWaves());
}
void OnDestroy()
{
Instance = null;
if(_panelHandle != null)
{
_panelHandle.Release();
_panelHandle = null;
}
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(StartWait);
while (true)
{
for (int i = 0; i < EnemyCount; i++)
{
var enemyLocation= _enemyLocations[Random.Range(0, 4)];
Vector3 spawnPosition = new Vector3(Random.Range(-SpawnValues.x, SpawnValues.x), SpawnValues.y, SpawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
if(enemyLocation == "enemy_ship")
{
var handle = YooAssets.LoadAssetSync<GameObject>(enemyLocation);
var go = handle.InstantiateSync(spawnPosition, spawnRotation);
var bhv = go.GetComponent<EntityEnemy>();
bhv.InitEntity(handle);
}
else
{
var handle = YooAssets.LoadAssetSync<GameObject>(enemyLocation);
var go = handle.InstantiateSync(spawnPosition, spawnRotation);
var bhv = go.GetComponent<EntityAsteroid>();
bhv.InitEntity(handle);
}
yield return new WaitForSeconds(SpawnWait);
}
yield return new WaitForSeconds(WaveWait);
if (_gameOver)
{
break;
}
}
}
public void GameOver()
{
_gameOver = true;
BattleEventDispatcher.SendGameOverMsg();
}
public void AddScore(int score)
{
_totalScore += score;
BattleEventDispatcher.SendScoreChangeMsg(_totalScore);
}
}
@@ -1,52 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
public class EntityAsteroid : MonoBehaviour
{
private AssetOperationHandle _ownerHandle;
public float MoveSpeed = -5f;
public float Tumble = 5f;
public void InitEntity(AssetOperationHandle ownerHandle)
{
_ownerHandle = ownerHandle;
}
void Awake()
{
var rigidBody = this.transform.GetComponent<Rigidbody>();
rigidBody.velocity = this.transform.forward * MoveSpeed;
rigidBody.angularVelocity = Random.insideUnitSphere * Tumble;
}
void OnDestroy()
{
if (_ownerHandle != null)
{
_ownerHandle.Release();
_ownerHandle = null;
}
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("PlayerBullet"))
{
var handle = YooAssets.LoadAssetSync<GameObject>("explosion_asteroid");
var go = handle.InstantiateSync(other.transform.position, Quaternion.identity);
var bhv = go.GetComponent<EntityEffect>();
bhv.InitEntity(handle);
BattleRoom.Instance.AddScore(1);
GameObject.Destroy(this.gameObject);
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Boundary"))
{
GameObject.Destroy(this.gameObject);
}
}
}
@@ -1,34 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
public class EntityEffect : MonoBehaviour
{
private AssetOperationHandle _ownerHandle;
public float DelayDestroyTime = 1f;
public void InitEntity(AssetOperationHandle ownerHandle)
{
_ownerHandle = ownerHandle;
}
void Awake()
{
Invoke(nameof(DelayDestroy), DelayDestroyTime);
}
void OnDestroy()
{
if (_ownerHandle != null)
{
_ownerHandle.Release();
_ownerHandle = null;
}
}
private void DelayDestroy()
{
GameObject.Destroy(this.gameObject);
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: c64420b3b1ae37943b4565f458c10b7d
guid: e2f6bcc746b3d984e81caafa7d25467b
folderAsset: yes
DefaultImporter:
externalObjects: {}
@@ -1,7 +1,7 @@
using System;
using UnityEngine;
public class BackgroundScroller : MonoBehaviour
public class BhvBackgroundScroller : MonoBehaviour
{
public float ScrollSpeed;
public float TileSizeZ;
@@ -0,0 +1,39 @@
using UnityEngine;
using UniFramework.Event;
using UniFramework.Module;
using YooAsset;
public class Boot : MonoBehaviour
{
/// <summary>
/// 资源系统运行模式
/// </summary>
public EPlayMode PlayMode = EPlayMode.EditorSimulateMode;
void Awake()
{
Debug.Log($"资源系统运行模式:{PlayMode}");
Application.targetFrameRate = 60;
Application.runInBackground = true;
}
void Start()
{
// 初始化BetterStreaming
BetterStreamingAssets.Initialize();
// 初始化事件系统
UniEvent.Initalize();
// 初始化管理系统
UniModule.Initialize();
// 初始化资源系统
YooAssets.Initialize();
// 创建补丁管理器
UniModule.CreateModule<PatchManager>();
// 开始补丁更新流程
PatchManager.Instance.Run(PlayMode);
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 1a79eedc3fa88c8429b085954a7e9093
guid: 8428e7a0bb96bf946aa3034281990090
folderAsset: yes
DefaultImporter:
externalObjects: {}
@@ -0,0 +1,119 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Event;
public class BattleEventDefine
{
/// <summary>
/// 分数改变
/// </summary>
public class ScoreChange : IEventMessage
{
public int CurrentScores;
public static void SendEventMessage(int currentScores)
{
var msg = new ScoreChange();
msg.CurrentScores = currentScores;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 游戏结束
/// </summary>
public class GameOver : IEventMessage
{
public static void SendEventMessage()
{
var msg = new GameOver();
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 敌人死亡
/// </summary>
public class EnemyDead : IEventMessage
{
public Vector3 Position;
public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation)
{
var msg = new EnemyDead();
msg.Position = position;
msg.Rotation = rotation;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 玩家死亡
/// </summary>
public class PlayerDead : IEventMessage
{
public Vector3 Position;
public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation)
{
var msg = new PlayerDead();
msg.Position = position;
msg.Rotation = rotation;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 小行星爆炸
/// </summary>
public class AsteroidExplosion : IEventMessage
{
public Vector3 Position;
public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation)
{
var msg = new AsteroidExplosion();
msg.Position = position;
msg.Rotation = rotation;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 敌人发射子弹
/// </summary>
public class EnemyFireBullet : IEventMessage
{
public Vector3 Position;
public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation)
{
var msg = new EnemyFireBullet();
msg.Position = position;
msg.Rotation = rotation;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 玩家发射子弹
/// </summary>
public class PlayerFireBullet : IEventMessage
{
public Vector3 Position;
public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation)
{
var msg = new PlayerFireBullet();
msg.Position = position;
msg.Rotation = rotation;
UniEvent.SendMessage(msg);
}
}
}
@@ -0,0 +1,98 @@
using UniFramework.Event;
public class PatchEventDefine
{
/// <summary>
/// 补丁流程步骤改变
/// </summary>
public class PatchStatesChange : IEventMessage
{
public string Tips;
public static void SendEventMessage(string tips)
{
var msg = new PatchStatesChange();
msg.Tips = tips;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 发现更新文件
/// </summary>
public class FoundUpdateFiles : IEventMessage
{
public int TotalCount;
public long TotalSizeBytes;
public static void SendEventMessage(int totalCount, long totalSizeBytes)
{
var msg = new FoundUpdateFiles();
msg.TotalCount = totalCount;
msg.TotalSizeBytes = totalSizeBytes;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 下载进度更新
/// </summary>
public class DownloadProgressUpdate : IEventMessage
{
public int TotalDownloadCount;
public int CurrentDownloadCount;
public long TotalDownloadSizeBytes;
public long CurrentDownloadSizeBytes;
public static void SendEventMessage(int totalDownloadCount, int currentDownloadCount, long totalDownloadSizeBytes, long currentDownloadSizeBytes)
{
var msg = new DownloadProgressUpdate();
msg.TotalDownloadCount = totalDownloadCount;
msg.CurrentDownloadCount = currentDownloadCount;
msg.TotalDownloadSizeBytes = totalDownloadSizeBytes;
msg.CurrentDownloadSizeBytes = currentDownloadSizeBytes;
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 资源版本号更新失败
/// </summary>
public class PackageVersionUpdateFailed : IEventMessage
{
public static void SendEventMessage()
{
var msg = new PackageVersionUpdateFailed();
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 补丁清单更新失败
/// </summary>
public class PatchManifestUpdateFailed : IEventMessage
{
public static void SendEventMessage()
{
var msg = new PatchManifestUpdateFailed();
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 网络文件下载失败
/// </summary>
public class WebFileDownloadFailed : IEventMessage
{
public string FileName;
public string Error;
public static void SendEventMessage(string fileName, string error)
{
var msg = new WebFileDownloadFailed();
msg.FileName = fileName;
msg.Error = error;
UniEvent.SendMessage(msg);
}
}
}
@@ -0,0 +1,22 @@
using UniFramework.Event;
public class SceneEventDefine
{
public class ChangeToHomeScene : IEventMessage
{
public static void SendEventMessage()
{
var msg = new ChangeToHomeScene();
UniEvent.SendMessage(msg);
}
}
public class ChangeToBattleScene : IEventMessage
{
public static void SendEventMessage()
{
var msg = new ChangeToBattleScene();
UniEvent.SendMessage(msg);
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 195a0b4317373b44d9289d7b0529eb7c
guid: c56a83939686d3a4aa76b7d4ec704889
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -0,0 +1,52 @@
using UniFramework.Event;
public class UserEventDefine
{
/// <summary>
/// 用户开始下载网络文件
/// </summary>
public class UserBeginDownloadWebFiles : IEventMessage
{
public static void SendEventMessage()
{
var msg = new UserBeginDownloadWebFiles();
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 用户尝试再次更新静态版本
/// </summary>
public class UserTryUpdatePackageVersion : IEventMessage
{
public static void SendEventMessage()
{
var msg = new UserTryUpdatePackageVersion();
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 用户尝试再次更新补丁清单
/// </summary>
public class UserTryUpdatePatchManifest : IEventMessage
{
public static void SendEventMessage()
{
var msg = new UserTryUpdatePatchManifest();
UniEvent.SendMessage(msg);
}
}
/// <summary>
/// 用户尝试再次下载网络文件
/// </summary>
public class UserTryDownloadWebFiles : IEventMessage
{
public static void SendEventMessage()
{
var msg = new UserTryDownloadWebFiles();
UniEvent.SendMessage(msg);
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 9f3747f3c9166b74f946fcdfde7f7827
guid: 1bfe7ffc460fb234da96624844ab7e51
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: cb1f2313c4b23304f9257ac58c1024f8
guid: 2673676235c2ebf4790768011d015d1d
folderAsset: yes
DefaultImporter:
externalObjects: {}
@@ -0,0 +1,43 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Pooling;
public class EntityAsteroid : MonoBehaviour
{
public float MoveSpeed = -5f;
public float Tumble = 5f;
private SpawnHandle _handle;
private Rigidbody _rigidbody;
public void InitEntity(SpawnHandle handle)
{
_handle = handle;
_rigidbody.velocity = this.transform.forward * MoveSpeed;
_rigidbody.angularVelocity = Random.insideUnitSphere * Tumble;
}
void Awake()
{
_rigidbody = this.transform.GetComponent<Rigidbody>();
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("PlayerBullet"))
{
BattleEventDefine.AsteroidExplosion.SendEventMessage(this.transform.position, this.transform.rotation);
_handle.Restore();
_handle = null;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Boundary"))
{
_handle.Restore();
_handle = null;
}
}
}
@@ -1,32 +1,25 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
using UniFramework.Pooling;
public class EntityBullet : MonoBehaviour
{
private AssetOperationHandle _ownerHandle;
public float MoveSpeed = 20f;
public float DelayDestroyTime = 5f;
public void InitEntity(AssetOperationHandle ownerHandle)
private SpawnHandle _handle;
private Rigidbody _rigidbody;
public void InitEntity(SpawnHandle handle)
{
_ownerHandle = ownerHandle;
_handle = handle;
_rigidbody.velocity = this.transform.forward * MoveSpeed;
}
void Awake()
{
var rigidBody = this.transform.GetComponent<Rigidbody>();
rigidBody.velocity = this.transform.forward * MoveSpeed;
}
void OnDestroy()
{
if (_ownerHandle != null)
{
_ownerHandle.Release();
_ownerHandle = null;
}
_rigidbody = this.transform.GetComponent<Rigidbody>();
}
void OnTriggerEnter(Collider other)
{
@@ -36,20 +29,27 @@ public class EntityBullet : MonoBehaviour
if (this.gameObject.CompareTag("EnemyBullet"))
{
if (other.CompareTag("Enemy") == false)
GameObject.Destroy(this.gameObject);
{
_handle.Restore();
_handle = null;
}
}
if (this.gameObject.CompareTag("PlayerBullet"))
{
if (other.CompareTag("Player") == false)
GameObject.Destroy(this.gameObject);
{
_handle.Restore();
_handle = null;
}
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Boundary"))
{
GameObject.Destroy(this.gameObject);
_handle.Restore();
_handle = null;
}
}
}
@@ -0,0 +1,23 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Pooling;
public class EntityEffect : MonoBehaviour
{
public float DelayDestroyTime = 1f;
private SpawnHandle _handle;
public void InitEntity(SpawnHandle handle)
{
_handle = handle;
Invoke(nameof(DelayDestroy), DelayDestroyTime);
}
private void DelayDestroy()
{
_handle.Restore();
_handle = null;
}
}
@@ -1,7 +1,7 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
using UniFramework.Pooling;
using Random = UnityEngine.Random;
public class EntityEnemy : MonoBehaviour
@@ -9,8 +9,6 @@ public class EntityEnemy : MonoBehaviour
private const float Dodge = 5f;
private const float Smoothing = 7.5f;
private AssetOperationHandle _ownerHandle;
public RoomBoundary Boundary;
public float MoveSpeed = 20f;
public float FireInterval = 2f;
@@ -19,17 +17,24 @@ public class EntityEnemy : MonoBehaviour
public Vector2 ManeuverTime = new Vector2(1, 2);
public Vector2 ManeuverWait = new Vector2(1, 2);
private SpawnHandle _handle;
private Transform _shotSpawn;
private Rigidbody _rigidbody;
private AudioSource _audioSource;
private float _lastFireTime = 0f;
private float _currentSpeed;
private float _targetManeuver;
float _currentSpeed;
float targetManeuver;
public void InitEntity(AssetOperationHandle ownerHandle)
public void InitEntity(SpawnHandle handle)
{
_ownerHandle = ownerHandle;
_handle = handle;
_rigidbody.velocity = this.transform.forward * -5f;
_lastFireTime = Time.time;
_currentSpeed = _rigidbody.velocity.z;
_targetManeuver = 0f;
StartCoroutine(Evade());
}
void Awake()
@@ -37,40 +42,19 @@ public class EntityEnemy : MonoBehaviour
_rigidbody = this.gameObject.GetComponent<Rigidbody>();
_audioSource = this.gameObject.GetComponent<AudioSource>();
_shotSpawn = this.transform.Find("shot_spawn");
_rigidbody.velocity = this.transform.forward * -5f;
_currentSpeed = _rigidbody.velocity.z;
StartCoroutine(Evade());
}
void Start()
{
_lastFireTime = Time.time;
}
void OnDestroy()
{
if (_ownerHandle != null)
{
_ownerHandle.Release();
_ownerHandle = null;
}
}
void Update()
{
if (Time.time - _lastFireTime >= FireInterval)
{
_lastFireTime = Time.time;
var handle = YooAssets.LoadAssetSync<GameObject>("enemy_bullet");
var go = handle.InstantiateSync(_shotSpawn.position, _shotSpawn.rotation);
var bhv = go.GetComponent<EntityBullet>();
bhv.InitEntity(handle);
_audioSource.Play();
BattleEventDefine.EnemyFireBullet.SendEventMessage(_shotSpawn.position, _shotSpawn.rotation);
}
}
void FixedUpdate()
{
float newManeuver = Mathf.MoveTowards(_rigidbody.velocity.x, targetManeuver, Smoothing * Time.deltaTime);
float newManeuver = Mathf.MoveTowards(_rigidbody.velocity.x, _targetManeuver, Smoothing * Time.deltaTime);
_rigidbody.velocity = new Vector3(newManeuver, 0.0f, _currentSpeed);
_rigidbody.position = new Vector3
(
@@ -86,20 +70,17 @@ public class EntityEnemy : MonoBehaviour
{
if (other.CompareTag("PlayerBullet"))
{
var handle = YooAssets.LoadAssetSync<GameObject>("explosion_enemy");
var go = handle.InstantiateSync(this.transform.position, this.transform.rotation);
var bhv = go.GetComponent<EntityEffect>();
bhv.InitEntity(handle);
BattleRoom.Instance.AddScore(10);
GameObject.Destroy(this.gameObject);
BattleEventDefine.EnemyDead.SendEventMessage(this.transform.position, this.transform.rotation);
_handle.Restore();
_handle = null;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Boundary"))
{
GameObject.Destroy(this.gameObject);
_handle.Restore();
_handle = null;
}
}
@@ -108,9 +89,9 @@ public class EntityEnemy : MonoBehaviour
yield return new WaitForSeconds(Random.Range(StartWait.x, StartWait.y));
while (true)
{
targetManeuver = Random.Range(1, Dodge) * -Mathf.Sign(transform.position.x);
_targetManeuver = Random.Range(1, Dodge) * -Mathf.Sign(transform.position.x);
yield return new WaitForSeconds(Random.Range(ManeuverTime.x, ManeuverTime.y));
targetManeuver = 0;
_targetManeuver = 0;
yield return new WaitForSeconds(Random.Range(ManeuverWait.x, ManeuverWait.y));
}
}
@@ -1,24 +1,23 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
using UniFramework.Pooling;
public class EntityPlayer : MonoBehaviour
{
private AssetOperationHandle _ownerHandle;
{
public RoomBoundary Boundary;
public float MoveSpeed = 10f;
public float FireRate = 0.25f;
private SpawnHandle _handle;
private float _nextFireTime = 0f;
private Transform _shotSpawn;
private Rigidbody _rigidbody;
private AudioSource _audioSource;
public void InitEntity(AssetOperationHandle ownerHandle)
public void InitEntity(SpawnHandle handle)
{
_ownerHandle = ownerHandle;
_handle = handle;
}
void Awake()
@@ -27,26 +26,13 @@ public class EntityPlayer : MonoBehaviour
_audioSource = this.gameObject.GetComponent<AudioSource>();
_shotSpawn = this.transform.Find("shot_spawn");
}
void OnDestroy()
{
if (_ownerHandle != null)
{
_ownerHandle.Release();
_ownerHandle = null;
}
}
void Update()
{
if (Input.GetButton("Fire1") && Time.time > _nextFireTime)
{
_nextFireTime = Time.time + FireRate;
var handle = YooAssets.LoadAssetSync<GameObject>("player_bullet");
var go = handle.InstantiateSync(_shotSpawn.position, _shotSpawn.rotation);
var bhv = go.GetComponent<EntityBullet>();
bhv.InitEntity(handle);
_audioSource.Play();
BattleEventDefine.PlayerFireBullet.SendEventMessage(_shotSpawn.position, _shotSpawn.rotation);
}
}
void FixedUpdate()
@@ -56,7 +42,6 @@ public class EntityPlayer : MonoBehaviour
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
_rigidbody.velocity = movement * MoveSpeed;
_rigidbody.position = new Vector3
(
Mathf.Clamp(GetComponent<Rigidbody>().position.x, Boundary.xMin, Boundary.xMax),
@@ -71,13 +56,9 @@ public class EntityPlayer : MonoBehaviour
{
if (other.CompareTag("Enemy") || other.CompareTag("EnemyBullet") || other.CompareTag("Asteroid"))
{
var explosionHandle = YooAssets.LoadAssetSync<GameObject>("explosion_player");
var go = explosionHandle.InstantiateSync(this.transform.position, this.transform.rotation);
var bhv = go.GetComponent<EntityEffect>();
bhv.InitEntity(explosionHandle);
BattleRoom.Instance.GameOver();
GameObject.Destroy(this.gameObject);
BattleEventDefine.PlayerDead.SendEventMessage(this.transform.position, this.transform.rotation);
_handle.Restore();
_handle = null;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: beab7f759234b61469afb94f517f959b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Pooling;
using UniFramework.Window;
using UniFramework.Machine;
using YooAsset;
internal class FsmInitGame : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
var handle = YooAssets.LoadAssetSync<GameObject>("UICanvas");
var canvas = handle.InstantiateSync();
var desktop = canvas.transform.Find("Desktop").gameObject;
GameObject.DontDestroyOnLoad(canvas);
// 初始化窗口系统
UniWindow.Initalize(desktop);
// 初始化对象池系统
UniPooling.Initalize();
_machine.ChangeState<FsmSceneHome>();
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 1e0ee5b75a4bc4b49b08f174399b9f01
guid: 35d459ebb0d7dc947b7b62d1f64a412f
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -0,0 +1,48 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Window;
using UniFramework.Event;
using UniFramework.Machine;
using UniFramework.Module;
using YooAsset;
internal class FsmSceneBattle : IStateNode
{
private BattleRoom _battleRoom;
void IStateNode.OnCreate(StateMachine machine)
{
}
void IStateNode.OnEnter()
{
UniWindow.OpenWindowSync<UILoadingWindow>("UILoading");
UniModule.StartCoroutine(Prepare());
}
void IStateNode.OnUpdate()
{
if(_battleRoom != null)
_battleRoom.UpdateRoom();
}
void IStateNode.OnExit()
{
if(_battleRoom != null)
{
_battleRoom.DestroyRoom();
_battleRoom = null;
}
}
private IEnumerator Prepare()
{
yield return YooAssets.LoadSceneAsync("scene_battle");
_battleRoom = new BattleRoom();
yield return _battleRoom.LoadRoom();
// 等所有数据准备完毕后,关闭加载界面。
UniWindow.CloseWindow<UILoadingWindow>();
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 5915c7b5006a8384dbefdf32da34a3e6
guid: 54061fd8bcab2344e87b0faf0464c179
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -0,0 +1,41 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Window;
using UniFramework.Module;
using YooAsset;
internal class FsmSceneHome : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
if (_machine.PreviousNode != typeof(FsmInitGame).FullName)
UniWindow.OpenWindowSync<UILoadingWindow>("UILoading");
UniModule.StartCoroutine(Prepare());
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
UniWindow.CloseWindow<UIHomeWindow>();
}
private IEnumerator Prepare()
{
yield return YooAssets.LoadSceneAsync("scene_home");
yield return UniWindow.OpenWindowAsync<UIHomeWindow>("UIHome");
yield return new WaitForSeconds(0.5f);
// 等所有数据准备完毕后,关闭加载界面。
UniWindow.CloseWindow<UILoadingWindow>();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 41730f8e5f2b6e64abc4a03035c61ea5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,64 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Event;
using UniFramework.Machine;
using UniFramework.Module;
public class GameManager : ModuleSingleton<GameManager>, IModule
{
private bool _isRun = false;
private EventGroup _eventGroup = new EventGroup();
private StateMachine _machine;
void IModule.OnCreate(object createParam)
{
}
void IModule.OnDestroy()
{
_eventGroup.RemoveAllListener();
}
void IModule.OnUpdate()
{
if (_machine != null)
_machine.Update();
}
public void Run()
{
if (_isRun == false)
{
_isRun = true;
// 注册监听事件
_eventGroup.AddListener<SceneEventDefine.ChangeToHomeScene>(OnHandleEventMessage);
_eventGroup.AddListener<SceneEventDefine.ChangeToBattleScene>(OnHandleEventMessage);
Debug.Log("开启游戏流程...");
_machine = new StateMachine(this);
_machine.AddNode<FsmInitGame>();
_machine.AddNode<FsmSceneHome>();
_machine.AddNode<FsmSceneBattle>();
_machine.Run<FsmInitGame>();
}
else
{
Debug.LogWarning("补丁更新已经正在进行中!");
}
}
/// <summary>
/// 接收事件
/// </summary>
private void OnHandleEventMessage(IEventMessage message)
{
if(message is SceneEventDefine.ChangeToHomeScene)
{
_machine.ChangeState<FsmSceneHome>();
}
else if(message is SceneEventDefine.ChangeToBattleScene)
{
_machine.ChangeState<FsmSceneBattle>();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f6630e7de79efb24b9263519ba4282e1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7866629ff257c6d4d84cd9dab5d0b000
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,257 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Window;
using UniFramework.Pooling;
using UniFramework.Event;
using UniFramework.Utility;
using YooAsset;
using Random = UnityEngine.Random;
[Serializable]
public class RoomBoundary
{
public float xMin, xMax, zMin, zMax;
}
/// <summary>
/// 战斗房间
/// </summary>
public class BattleRoom
{
private enum ESteps
{
None,
Ready,
Spawn,
WaitSpawn,
WaitWave,
GameOver,
}
private EventGroup _eventGroup = new EventGroup();
private Spawner _entitySpawner;
private GameObject _roomRoot;
private AssetOperationHandle _musicHandle;
// 关卡参数
private const int EnemyCount = 10;
private const int EnemyScore = 10;
private const int AsteroidScore = 1;
private readonly Vector3 _spawnValues = new Vector3(6, 0, 20);
private readonly string[] _entityLocations = new string[]
{
"asteroid01", "asteroid02", "asteroid03", "enemy_ship"
};
private ESteps _steps = ESteps.None;
private int _totalScore = 0;
private int _waveSpawnCount = 0;
private UniTimer _startWaitTimer = UniTimer.CreateOnceTimer(1f);
private UniTimer _spawnWaitTimer = UniTimer.CreateOnceTimer(0.75f);
private UniTimer _waveWaitTimer = UniTimer.CreateOnceTimer(4f);
/// <summary>
/// 销毁房间
/// </summary>
public void DestroyRoom()
{
if (_musicHandle != null)
_musicHandle.Release();
if (_eventGroup != null)
_eventGroup.RemoveAllListener();
if (_entitySpawner != null)
_entitySpawner.DestroyAll(true);
if (_roomRoot != null)
GameObject.Destroy(_roomRoot);
UniWindow.CloseWindow<UIBattleWindow>();
}
/// <summary>
/// 更新房间
/// </summary>
public void UpdateRoom()
{
if (_steps == ESteps.None || _steps == ESteps.GameOver)
return;
if (_steps == ESteps.Ready)
{
if (_startWaitTimer.Update(Time.deltaTime))
{
_steps = ESteps.Spawn;
}
}
if (_steps == ESteps.Spawn)
{
var enemyLocation = _entityLocations[Random.Range(0, 4)];
Vector3 spawnPosition = new Vector3(Random.Range(-_spawnValues.x, _spawnValues.x), _spawnValues.y, _spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
if (enemyLocation == "enemy_ship")
{
// 生成敌人实体
var handle = _entitySpawner.SpawnSync(enemyLocation, _roomRoot.transform, spawnPosition, spawnRotation);
var entity = handle.GameObj.GetComponent<EntityEnemy>();
entity.InitEntity(handle);
}
else
{
// 生成小行星实体
var handle = _entitySpawner.SpawnSync(enemyLocation, _roomRoot.transform, spawnPosition, spawnRotation);
var entity = handle.GameObj.GetComponent<EntityAsteroid>();
entity.InitEntity(handle);
}
_waveSpawnCount++;
if (_waveSpawnCount >= EnemyCount)
{
_steps = ESteps.WaitWave;
}
else
{
_steps = ESteps.WaitSpawn;
}
}
if (_steps == ESteps.WaitSpawn)
{
if (_spawnWaitTimer.Update(Time.deltaTime))
{
_spawnWaitTimer.Reset();
_steps = ESteps.Spawn;
}
}
if (_steps == ESteps.WaitWave)
{
if (_waveWaitTimer.Update(Time.deltaTime))
{
_waveWaitTimer.Reset();
_waveSpawnCount = 0;
_steps = ESteps.Spawn;
}
}
}
/// <summary>
/// 加载房间
/// </summary>
public IEnumerator LoadRoom()
{
// 创建房间根对象
_roomRoot = new GameObject("BattleRoom");
// 加载背景音乐
_musicHandle = YooAssets.LoadAssetAsync<AudioClip>("music_background");
yield return _musicHandle;
// 播放背景音乐
var audioSource = _roomRoot.AddComponent<AudioSource>();
audioSource.loop = true;
audioSource.clip = _musicHandle.AssetObject as AudioClip;
audioSource.Play();
// 创建游戏对象发生器
_entitySpawner = UniPooling.CreateSpawner("DefaultPackage");
// 创建游戏对象池
yield return _entitySpawner.CreateGameObjectPoolAsync("player_ship");
yield return _entitySpawner.CreateGameObjectPoolAsync("player_bullet");
yield return _entitySpawner.CreateGameObjectPoolAsync("enemy_ship");
yield return _entitySpawner.CreateGameObjectPoolAsync("enemy_bullet");
yield return _entitySpawner.CreateGameObjectPoolAsync("asteroid01");
yield return _entitySpawner.CreateGameObjectPoolAsync("asteroid02");
yield return _entitySpawner.CreateGameObjectPoolAsync("asteroid03");
yield return _entitySpawner.CreateGameObjectPoolAsync("explosion_asteroid");
yield return _entitySpawner.CreateGameObjectPoolAsync("explosion_enemy");
yield return _entitySpawner.CreateGameObjectPoolAsync("explosion_player");
// 创建玩家实体对象
var handle = _entitySpawner.SpawnSync("player_ship");
var entity = handle.GameObj.GetComponent<EntityPlayer>();
entity.InitEntity(handle);
// 显示战斗界面
yield return UniWindow.OpenWindowAsync<UIBattleWindow>("UIBattle");
// 监听游戏事件
_eventGroup.AddListener<BattleEventDefine.PlayerDead>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.EnemyDead>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.AsteroidExplosion>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.PlayerFireBullet>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.EnemyFireBullet>(OnHandleEventMessage);
_steps = ESteps.Ready;
}
/// <summary>
/// 接收事件
/// </summary>
/// <param name="message"></param>
private void OnHandleEventMessage(IEventMessage message)
{
if (message is BattleEventDefine.PlayerDead)
{
var msg = message as BattleEventDefine.PlayerDead;
// 创建爆炸效果
var handle = _entitySpawner.SpawnSync("explosion_player", _roomRoot.transform, msg.Position, msg.Rotation);
var entity = handle.GameObj.GetComponent<EntityEffect>();
entity.InitEntity(handle);
_steps = ESteps.GameOver;
BattleEventDefine.GameOver.SendEventMessage();
}
else if (message is BattleEventDefine.EnemyDead)
{
var msg = message as BattleEventDefine.EnemyDead;
// 创建爆炸效果
var handle = _entitySpawner.SpawnSync("explosion_enemy", _roomRoot.transform, msg.Position, msg.Rotation);
var entity = handle.GameObj.GetComponent<EntityEffect>();
entity.InitEntity(handle);
_totalScore += EnemyScore;
BattleEventDefine.ScoreChange.SendEventMessage(_totalScore);
}
else if (message is BattleEventDefine.AsteroidExplosion)
{
var msg = message as BattleEventDefine.AsteroidExplosion;
// 创建爆炸效果
var handle = _entitySpawner.SpawnSync("explosion_asteroid", _roomRoot.transform, msg.Position, msg.Rotation);
var entity = handle.GameObj.GetComponent<EntityEffect>();
entity.InitEntity(handle);
_totalScore += AsteroidScore;
BattleEventDefine.ScoreChange.SendEventMessage(_totalScore);
}
else if (message is BattleEventDefine.PlayerFireBullet)
{
var msg = message as BattleEventDefine.PlayerFireBullet;
// 创建子弹实体
var handle = _entitySpawner.SpawnSync("player_bullet", _roomRoot.transform, msg.Position, msg.Rotation);
var entity = handle.GameObj.GetComponent<EntityBullet>();
entity.InitEntity(handle);
}
else if (message is BattleEventDefine.EnemyFireBullet)
{
var msg = message as BattleEventDefine.EnemyFireBullet;
// 创建子弹实体
var handle = _entitySpawner.SpawnSync("enemy_bullet", _roomRoot.transform, msg.Position, msg.Rotation);
var entity = handle.GameObj.GetComponent<EntityBullet>();
entity.InitEntity(handle);
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 43ab5a1b8ae5c2b4a8995952e7e01f3f
guid: d4dfc5f1cace4e8469e496d83b254ac7
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -1,45 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
public class EventGroup
{
private readonly Dictionary<System.Type, List<Action<IEventMessage>>> _cachedListener = new Dictionary<System.Type, List<Action<IEventMessage>>>();
/// <summary>
/// 添加一个监听
/// </summary>
public void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
{
System.Type eventType = typeof(TEvent);
if (_cachedListener.ContainsKey(eventType) == false)
_cachedListener.Add(eventType, new List<Action<IEventMessage>>());
if (_cachedListener[eventType].Contains(listener) == false)
{
_cachedListener[eventType].Add(listener);
EventManager.AddListener(eventType, listener);
}
else
{
UnityEngine.Debug.LogWarning($"Event listener is exist : {eventType}");
}
}
/// <summary>
/// 移除所有缓存的监听
/// </summary>
public void RemoveAllListener()
{
foreach (var pair in _cachedListener)
{
System.Type eventType = pair.Key;
for (int i = 0; i < pair.Value.Count; i++)
{
EventManager.RemoveListener(eventType, pair.Value[i]);
}
pair.Value.Clear();
}
_cachedListener.Clear();
}
}
@@ -1,171 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// 事件管理器
/// </summary>
public static class EventManager
{
private class PostWrapper
{
public int PostFrame;
public int EventID;
public IEventMessage Message;
public void OnRelease()
{
PostFrame = 0;
EventID = 0;
Message = null;
}
}
private static readonly Dictionary<int, List<Action<IEventMessage>>> _listeners = new Dictionary<int, List<Action<IEventMessage>>>(1000);
private static readonly List<PostWrapper> _postWrappers = new List<PostWrapper>(1000);
public static void Update()
{
for (int i = _postWrappers.Count - 1; i >= 0; i--)
{
var wrapper = _postWrappers[i];
if (UnityEngine.Time.frameCount > wrapper.PostFrame)
{
SendMessage(wrapper.EventID, wrapper.Message);
_postWrappers.RemoveAt(i);
}
}
}
/// <summary>
/// 添加监听
/// </summary>
public static void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
{
AddListener(typeof(TEvent), listener);
}
/// <summary>
/// 添加监听
/// </summary>
public static void AddListener(System.Type eventType, System.Action<IEventMessage> listener)
{
int eventId = eventType.GetHashCode();
AddListener(eventId, listener);
}
/// <summary>
/// 添加监听
/// </summary>
public static void AddListener(int eventId, System.Action<IEventMessage> listener)
{
if (_listeners.ContainsKey(eventId) == false)
_listeners.Add(eventId, new List<Action<IEventMessage>>());
if (_listeners[eventId].Contains(listener) == false)
_listeners[eventId].Add(listener);
}
/// <summary>
/// 移除监听
/// </summary>
public static void RemoveListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
{
RemoveListener(typeof(TEvent), listener);
}
/// <summary>
/// 移除监听
/// </summary>
public static void RemoveListener(System.Type eventType, System.Action<IEventMessage> listener)
{
int eventId = eventType.GetHashCode();
RemoveListener(eventId, listener);
}
/// <summary>
/// 移除监听
/// </summary>
public static void RemoveListener(int eventId, System.Action<IEventMessage> listener)
{
if (_listeners.ContainsKey(eventId))
{
if (_listeners[eventId].Contains(listener))
_listeners[eventId].Remove(listener);
}
}
/// <summary>
/// 实时广播事件
/// </summary>
public static void SendMessage(IEventMessage message)
{
int eventId = message.GetType().GetHashCode();
SendMessage(eventId, message);
}
/// <summary>
/// 实时广播事件
/// </summary>
public static void SendMessage(int eventId, IEventMessage message)
{
if (_listeners.ContainsKey(eventId) == false)
return;
List<Action<IEventMessage>> listeners = _listeners[eventId];
for (int i = listeners.Count - 1; i >= 0; i--)
{
listeners[i].Invoke(message);
}
}
/// <summary>
/// 延迟广播事件
/// </summary>
public static void PostMessage(IEventMessage message)
{
int eventId = message.GetType().GetHashCode();
PostMessage(eventId, message);
}
/// <summary>
/// 延迟广播事件
/// </summary>
public static void PostMessage(int eventId, IEventMessage message)
{
var wrapper = new PostWrapper();
wrapper.PostFrame = UnityEngine.Time.frameCount;
wrapper.EventID = eventId;
wrapper.Message = message;
_postWrappers.Add(wrapper);
}
/// <summary>
/// 清空所有监听
/// </summary>
public static void ClearListeners()
{
foreach (int eventId in _listeners.Keys)
{
_listeners[eventId].Clear();
}
_listeners.Clear();
}
/// <summary>
/// 获取监听者总数
/// </summary>
private static int GetAllListenerCount()
{
int count = 0;
foreach (var list in _listeners)
{
count += list.Value.Count;
}
return count;
}
}
@@ -1,4 +0,0 @@
public interface IEventMessage
{
}
@@ -1,121 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// 有限状态机
/// </summary>
public static class FsmManager
{
private static readonly List<IFsmNode> _nodes = new List<IFsmNode>();
private static IFsmNode _curNode;
private static IFsmNode _preNode;
/// <summary>
/// 当前运行的节点名称
/// </summary>
public static string CurrentNodeName
{
get { return _curNode != null ? _curNode.Name : string.Empty; }
}
/// <summary>
/// 之前运行的节点名称
/// </summary>
public static string PreviousNodeName
{
get { return _preNode != null ? _preNode.Name : string.Empty; }
}
/// <summary>
/// 启动状态机
/// </summary>
/// <param name="entryNode">入口节点</param>
public static void Run(string entryNode)
{
_curNode = GetNode(entryNode);
_preNode = GetNode(entryNode);
if (_curNode != null)
_curNode.OnEnter();
else
UnityEngine.Debug.LogError($"Not found entry node : {entryNode}");
}
/// <summary>
/// 更新状态机
/// </summary>
public static void Update()
{
if (_curNode != null)
_curNode.OnUpdate();
}
/// <summary>
/// 加入一个节点
/// </summary>
public static void AddNode(IFsmNode node)
{
if (node == null)
throw new ArgumentNullException();
if (_nodes.Contains(node) == false)
{
_nodes.Add(node);
}
else
{
UnityEngine.Debug.LogWarning($"Node {node.Name} already existed");
}
}
/// <summary>
/// 转换节点
/// </summary>
public static void Transition(string nodeName)
{
if (string.IsNullOrEmpty(nodeName))
throw new ArgumentNullException();
IFsmNode node = GetNode(nodeName);
if (node == null)
{
UnityEngine.Debug.LogError($"Can not found node {nodeName}");
return;
}
UnityEngine.Debug.Log($"FSM change {_curNode.Name} to {node.Name}");
_preNode = _curNode;
_curNode.OnExit();
_curNode = node;
_curNode.OnEnter();
}
/// <summary>
/// 返回到之前的节点
/// </summary>
public static void RevertToPreviousNode()
{
Transition(PreviousNodeName);
}
private static bool IsContains(string nodeName)
{
for (int i = 0; i < _nodes.Count; i++)
{
if (_nodes[i].Name == nodeName)
return true;
}
return false;
}
private static IFsmNode GetNode(string nodeName)
{
for (int i = 0; i < _nodes.Count; i++)
{
if (_nodes[i].Name == nodeName)
return _nodes[i];
}
return null;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: bcbf86a86eb115a41b6aa61fb0945d43
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,12 +0,0 @@
public interface IFsmNode
{
/// <summary>
/// 节点名称
/// </summary>
string Name { get; }
void OnEnter();
void OnUpdate();
void OnExit();
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 40fe73297598be84fb8dadedd4dd17e6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,31 +1,35 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
/// <summary>
/// 清理未使用的缓存文件
/// </summary>
internal class FsmClearCache : IFsmNode
internal class FsmClearCache : IStateNode
{
public string Name { private set; get; } = nameof(FsmClearCache);
private StateMachine _machine;
void IFsmNode.OnEnter()
void IStateNode.OnCreate(StateMachine machine)
{
Debug.Log("开始清理未使用的缓存文件!");
_machine = machine;
}
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("清理未使用的缓存文件!");
var package = YooAsset.YooAssets.GetAssetsPackage("DefaultPackage");
var operation = package.ClearPackageUnusedCacheFilesAsync();
operation.Completed += Operation_Completed;
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
private void Operation_Completed(YooAsset.AsyncOperationBase obj)
{
FsmManager.Transition(nameof(FsmStartGame));
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
_machine.ChangeState<FsmPatchDone>();
}
}
@@ -0,0 +1,56 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Module;
using YooAsset;
/// <summary>
/// 创建文件下载器
/// </summary>
public class FsmCreateDownloader : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("创建补丁下载器!");
UniModule.StartCoroutine(CreateDownloader());
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
IEnumerator CreateDownloader()
{
yield return new WaitForSecondsRealtime(0.5f);
int downloadingMaxNum = 10;
int failedTryAgain = 3;
var downloader = YooAssets.CreatePatchDownloader(downloadingMaxNum, failedTryAgain);
PatchManager.Instance.Downloader = downloader;
if (downloader.TotalDownloadCount == 0)
{
Debug.Log("没有发现需要下载的资源!");
_machine.ChangeState<FsmDownloadOver>();
}
else
{
Debug.Log($"一共发现了{downloader.TotalDownloadCount}个资源需要更新下载!");
// 发现新更新文件后,挂起流程系统
// 注意:开发者需要在下载前检测磁盘空间不足
int totalDownloadCount = downloader.TotalDownloadCount;
long totalDownloadBytes = downloader.TotalDownloadBytes;
PatchEventDefine.FoundUpdateFiles.SendEventMessage(totalDownloadCount, totalDownloadBytes);
}
}
}
@@ -0,0 +1,46 @@
using System.Collections;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Module;
using YooAsset;
/// <summary>
/// 下载更新文件
/// </summary>
public class FsmDownloadFiles : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("开始下载补丁文件!");
UniModule.StartCoroutine(BeginDownload());
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
private IEnumerator BeginDownload()
{
var downloader = PatchManager.Instance.Downloader;
// 注册下载回调
downloader.OnDownloadErrorCallback = PatchEventDefine.WebFileDownloadFailed.SendEventMessage;
downloader.OnDownloadProgressCallback = PatchEventDefine.DownloadProgressUpdate.SendEventMessage;
downloader.BeginDownload();
yield return downloader;
// 检测下载结果
if (downloader.Status != EOperationStatus.Succeed)
yield break;
_machine.ChangeState<FsmPatchDone>();
}
}
@@ -0,0 +1,27 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
/// <summary>
/// 下载完毕
/// </summary>
internal class FsmDownloadOver : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
_machine.ChangeState<FsmClearCache>();
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c96c57c65f74bb3469dc71b13ef78c84
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,31 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Module;
/// <summary>
/// 更新完毕
/// </summary>
internal class FsmPatchDone : IStateNode
{
void IStateNode.OnCreate(StateMachine machine)
{
}
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("开始游戏!");
// 创建游戏管理器
UniModule.CreateModule<GameManager>();
// 开启游戏流程
GameManager.Instance.Run();
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
}
@@ -1,45 +1,49 @@
using System;
using System.Collections;
using UnityEngine;
using YooAsset;
using Better.StreamingAssets;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Module;
using YooAsset;
public class GameBoot : MonoBehaviour
/// <summary>
/// 初始化工作
/// </summary>
internal class FsmPatchInit : IStateNode
{
public static GameBoot Instance;
private StateMachine _machine;
public EPlayMode PlayMode = EPlayMode.EditorSimulateMode;
void Awake()
void IStateNode.OnCreate(StateMachine machine)
{
Debug.Log($"资源系统运行模式:{PlayMode}");
Instance = this;
Application.targetFrameRate = 60;
Application.runInBackground = true;
DontDestroyOnLoad(this.gameObject);
_machine = machine;
}
void Update()
void IStateNode.OnEnter()
{
EventManager.Update();
FsmManager.Update();
}
IEnumerator Start()
{
// 初始化BetterStreaming
BetterStreamingAssets.Initialize();
// 加载更新面板
var go = Resources.Load<GameObject>("PatchWindow");
GameObject.Instantiate(go);
// 初始化资源系统
YooAssets.Initialize();
UniModule.StartCoroutine(InitYooAsset());
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
// 创建默认的资源包
private IEnumerator InitYooAsset()
{
var playMode = PatchManager.Instance.PlayMode;
// 创建默认的资源包
var package = YooAssets.CreateAssetsPackage("DefaultPackage");
YooAssets.SetDefaultAssetsPackage(package);
// 编辑器下的模拟模式
if (PlayMode == EPlayMode.EditorSimulateMode)
if (playMode == EPlayMode.EditorSimulateMode)
{
var createParameters = new EditorSimulateModeParameters();
createParameters.SimulatePatchManifestPath = EditorSimulateModeHelper.SimulateBuild("DefaultPackage");
@@ -47,7 +51,7 @@ public class GameBoot : MonoBehaviour
}
// 单机运行模式
if (PlayMode == EPlayMode.OfflinePlayMode)
if (playMode == EPlayMode.OfflinePlayMode)
{
var createParameters = new OfflinePlayModeParameters();
createParameters.DecryptionServices = new GameDecryptionServices();
@@ -55,7 +59,7 @@ public class GameBoot : MonoBehaviour
}
// 联机运行模式
if (PlayMode == EPlayMode.HostPlayMode)
if (playMode == EPlayMode.HostPlayMode)
{
var createParameters = new HostPlayModeParameters();
createParameters.DecryptionServices = new GameDecryptionServices();
@@ -65,10 +69,12 @@ public class GameBoot : MonoBehaviour
yield return package.InitializeAsync(createParameters);
}
// 运行资源更新流程
PatchManager.Run();
_machine.ChangeState<FsmUpdateVersion>();
}
/// <summary>
/// 获取资源服务器地址
/// </summary>
private string GetHostServerURL()
{
//string hostServerIP = "http://10.0.2.2"; //安卓模拟器地址
@@ -95,7 +101,10 @@ public class GameBoot : MonoBehaviour
return $"{hostServerIP}/CDN/PC/{gameVersion}";
#endif
}
/// <summary>
/// 内置文件查询服务类
/// </summary>
private class GameQueryServices : IQueryServices
{
public bool QueryStreamingAssets(string fileName)
@@ -105,6 +114,10 @@ public class GameBoot : MonoBehaviour
return BetterStreamingAssets.FileExists($"{buildinFolderName}/{fileName}");
}
}
/// <summary>
/// 资源文件解密服务类
/// </summary>
private class GameDecryptionServices : IDecryptionServices
{
public ulong LoadFromFileOffset(DecryptFileInfo fileInfo)
@@ -0,0 +1,49 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Module;
using YooAsset;
/// <summary>
/// 更新资源清单
/// </summary>
public class FsmUpdateManifest : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("更新资源清单!");
UniModule.StartCoroutine(UpdateManifest());
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
private IEnumerator UpdateManifest()
{
yield return new WaitForSecondsRealtime(0.5f);
var package = YooAssets.GetAssetsPackage("DefaultPackage");
var operation = package.UpdatePackageManifestAsync(PatchManager.Instance.PackageVersion, 30);
yield return operation;
if(operation.Status == EOperationStatus.Succeed)
{
_machine.ChangeState<FsmCreateDownloader>();
}
else
{
Debug.LogWarning(operation.Error);
PatchEventDefine.PatchManifestUpdateFailed.SendEventMessage();
}
}
}
@@ -0,0 +1,50 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Module;
using YooAsset;
/// <summary>
/// 更新资源版本号
/// </summary>
internal class FsmUpdateVersion : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("获取最新的资源版本 !");
UniModule.StartCoroutine(GetStaticVersion());
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
private IEnumerator GetStaticVersion()
{
yield return new WaitForSecondsRealtime(0.5f);
var package = YooAssets.GetAssetsPackage("DefaultPackage");
var operation = package.UpdatePackageVersionAsync(30);
yield return operation;
if (operation.Status == EOperationStatus.Succeed)
{
PatchManager.Instance.PackageVersion = operation.PackageVersion;
_machine.ChangeState<FsmUpdateManifest>();
}
else
{
Debug.LogWarning(operation.Error);
PatchEventDefine.PackageVersionUpdateFailed.SendEventMessage();
}
}
}
@@ -0,0 +1,105 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Event;
using UniFramework.Module;
using YooAsset;
public class PatchManager : ModuleSingleton<PatchManager>, IModule
{
/// <summary>
/// 运行模式
/// </summary>
public EPlayMode PlayMode { private set; get; }
/// <summary>
/// 包裹的版本信息
/// </summary>
public string PackageVersion { set; get; }
/// <summary>
/// 下载器
/// </summary>
public PatchDownloaderOperation Downloader { set; get; }
private bool _isRun = false;
private EventGroup _eventGroup = new EventGroup();
private StateMachine _machine;
void IModule.OnCreate(object createParam)
{
}
void IModule.OnDestroy()
{
_eventGroup.RemoveAllListener();
}
void IModule.OnUpdate()
{
if (_machine != null)
_machine.Update();
}
/// <summary>
/// 开启流程
/// </summary>
public void Run(EPlayMode playMode)
{
if (_isRun == false)
{
_isRun = true;
PlayMode = playMode;
// 注册监听事件
_eventGroup.AddListener<UserEventDefine.UserBeginDownloadWebFiles>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryUpdatePackageVersion>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryUpdatePatchManifest>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryDownloadWebFiles>(OnHandleEventMessage);
Debug.Log("开启补丁更新流程...");
_machine = new StateMachine(this);
_machine.AddNode<FsmPatchInit>();
_machine.AddNode<FsmUpdateVersion>();
_machine.AddNode<FsmUpdateManifest>();
_machine.AddNode<FsmCreateDownloader>();
_machine.AddNode<FsmDownloadFiles>();
_machine.AddNode<FsmDownloadOver>();
_machine.AddNode<FsmClearCache>();
_machine.AddNode<FsmPatchDone>();
_machine.Run<FsmPatchInit>();
}
else
{
Debug.LogWarning("补丁更新已经正在进行中!");
}
}
/// <summary>
/// 接收事件
/// </summary>
private void OnHandleEventMessage(IEventMessage message)
{
if (message is UserEventDefine.UserBeginDownloadWebFiles)
{
_machine.ChangeState<FsmDownloadFiles>();
}
else if (message is UserEventDefine.UserTryUpdatePackageVersion)
{
_machine.ChangeState<FsmUpdateVersion>();
}
else if (message is UserEventDefine.UserTryUpdatePatchManifest)
{
_machine.ChangeState<FsmUpdateManifest>();
}
else if (message is UserEventDefine.UserTryDownloadWebFiles)
{
_machine.ChangeState<FsmCreateDownloader>();
}
else
{
throw new System.NotImplementedException($"{message.GetType()}");
}
}
}
@@ -3,6 +3,7 @@ using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Event;
public class PatchWindow : MonoBehaviour
{
@@ -69,12 +70,12 @@ public class PatchWindow : MonoBehaviour
_messageBoxObj = transform.Find("UIWindow/MessgeBox").gameObject;
_messageBoxObj.SetActive(false);
_eventGroup.AddListener<PatchEventDefine.PatchStatesChange>(OnHandleEvent);
_eventGroup.AddListener<PatchEventDefine.FoundUpdateFiles>(OnHandleEvent);
_eventGroup.AddListener<PatchEventDefine.DownloadProgressUpdate>(OnHandleEvent);
_eventGroup.AddListener<PatchEventDefine.StaticVersionUpdateFailed>(OnHandleEvent);
_eventGroup.AddListener<PatchEventDefine.PatchManifestUpdateFailed>(OnHandleEvent);
_eventGroup.AddListener<PatchEventDefine.WebFileDownloadFailed>(OnHandleEvent);
_eventGroup.AddListener<PatchEventDefine.PatchStatesChange>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.FoundUpdateFiles>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.DownloadProgressUpdate>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.PackageVersionUpdateFailed>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.PatchManifestUpdateFailed>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.WebFileDownloadFailed>(OnHandleEventMessage);
}
void OnDestroy()
{
@@ -84,72 +85,61 @@ public class PatchWindow : MonoBehaviour
/// <summary>
/// 接收事件
/// </summary>
private void OnHandleEvent(IEventMessage msg)
private void OnHandleEventMessage(IEventMessage message)
{
if (msg is PatchEventDefine.PatchStatesChange)
if (message is PatchEventDefine.PatchStatesChange)
{
var message = msg as PatchEventDefine.PatchStatesChange;
if (message.CurrentStates == EPatchStates.UpdateStaticVersion)
_tips.text = "Update static version.";
else if (message.CurrentStates == EPatchStates.UpdateManifest)
_tips.text = "Update patch manifest.";
else if (message.CurrentStates == EPatchStates.CreateDownloader)
_tips.text = "Check download contents.";
else if (message.CurrentStates == EPatchStates.DownloadWebFiles)
_tips.text = "Downloading patch files.";
else if (message.CurrentStates == EPatchStates.PatchDone)
_tips.text = "Welcome to game world !";
else
throw new NotImplementedException(message.CurrentStates.ToString());
var msg = message as PatchEventDefine.PatchStatesChange;
_tips.text = msg.Tips;
}
else if (msg is PatchEventDefine.FoundUpdateFiles)
else if (message is PatchEventDefine.FoundUpdateFiles)
{
var message = msg as PatchEventDefine.FoundUpdateFiles;
var msg = message as PatchEventDefine.FoundUpdateFiles;
System.Action callback = () =>
{
PatchManager.HandleOperation(EPatchOperation.BeginDownloadWebFiles);
UserEventDefine.UserBeginDownloadWebFiles.SendEventMessage();
};
float sizeMB = message.TotalSizeBytes / 1048576f;
float sizeMB = msg.TotalSizeBytes / 1048576f;
sizeMB = Mathf.Clamp(sizeMB, 0.1f, float.MaxValue);
string totalSizeMB = sizeMB.ToString("f1");
ShowMessageBox($"Found update patch files, Total count {message.TotalCount} Total szie {totalSizeMB}MB", callback);
ShowMessageBox($"Found update patch files, Total count {msg.TotalCount} Total szie {totalSizeMB}MB", callback);
}
else if (msg is PatchEventDefine.DownloadProgressUpdate)
else if (message is PatchEventDefine.DownloadProgressUpdate)
{
var message = msg as PatchEventDefine.DownloadProgressUpdate;
_slider.value = (float)message.CurrentDownloadCount / message.TotalDownloadCount;
string currentSizeMB = (message.CurrentDownloadSizeBytes / 1048576f).ToString("f1");
string totalSizeMB = (message.TotalDownloadSizeBytes / 1048576f).ToString("f1");
_tips.text = $"{message.CurrentDownloadCount}/{message.TotalDownloadCount} {currentSizeMB}MB/{totalSizeMB}MB";
var msg = message as PatchEventDefine.DownloadProgressUpdate;
_slider.value = (float)msg.CurrentDownloadCount / msg.TotalDownloadCount;
string currentSizeMB = (msg.CurrentDownloadSizeBytes / 1048576f).ToString("f1");
string totalSizeMB = (msg.TotalDownloadSizeBytes / 1048576f).ToString("f1");
_tips.text = $"{msg.CurrentDownloadCount}/{msg.TotalDownloadCount} {currentSizeMB}MB/{totalSizeMB}MB";
}
else if (msg is PatchEventDefine.StaticVersionUpdateFailed)
else if (message is PatchEventDefine.PackageVersionUpdateFailed)
{
System.Action callback = () =>
{
PatchManager.HandleOperation(EPatchOperation.TryUpdateStaticVersion);
UserEventDefine.UserTryUpdatePackageVersion.SendEventMessage();
};
ShowMessageBox($"Failed to update static version, please check the network status.", callback);
}
else if (msg is PatchEventDefine.PatchManifestUpdateFailed)
else if (message is PatchEventDefine.PatchManifestUpdateFailed)
{
System.Action callback = () =>
{
PatchManager.HandleOperation(EPatchOperation.TryUpdatePatchManifest);
UserEventDefine.UserTryUpdatePatchManifest.SendEventMessage();
};
ShowMessageBox($"Failed to update patch manifest, please check the network status.", callback);
}
else if (msg is PatchEventDefine.WebFileDownloadFailed)
else if (message is PatchEventDefine.WebFileDownloadFailed)
{
var message = msg as PatchEventDefine.WebFileDownloadFailed;
var msg = message as PatchEventDefine.WebFileDownloadFailed;
System.Action callback = () =>
{
PatchManager.HandleOperation(EPatchOperation.TryDownloadWebFiles);
UserEventDefine.UserTryDownloadWebFiles.SendEventMessage();
};
ShowMessageBox($"Failed to download file : {message.FileName}", callback);
ShowMessageBox($"Failed to download file : {msg.FileName}", callback);
}
else
{
throw new System.NotImplementedException($"{msg.GetType()}");
throw new System.NotImplementedException($"{message.GetType()}");
}
}
@@ -1,26 +0,0 @@
/// <summary>
/// 用户层反馈的操作方式
/// </summary>
public enum EPatchOperation
{
/// <summary>
/// 开始下载网络文件
/// </summary>
BeginDownloadWebFiles,
/// <summary>
/// 尝试再次更新静态版本
/// </summary>
TryUpdateStaticVersion,
/// <summary>
/// 尝试再次更新补丁清单
/// </summary>
TryUpdatePatchManifest,
/// <summary>
/// 尝试再次下载网络文件
/// </summary>
TryDownloadWebFiles,
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 219b7f0e5d04432429b5fcb2207fa23b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,31 +0,0 @@
/// <summary>
/// 补丁系统更新状态
/// </summary>
public enum EPatchStates
{
/// <summary>
/// 更新静态的资源版本
/// </summary>
UpdateStaticVersion,
/// <summary>
/// 更新补丁清单
/// </summary>
UpdateManifest,
/// <summary>
/// 创建下载器
/// </summary>
CreateDownloader,
/// <summary>
/// 下载远端文件
/// </summary>
DownloadWebFiles,
/// <summary>
/// 补丁流程完毕
/// </summary>
PatchDone,
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 6f1f35b77d2285045b35f588be8f7236
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,49 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
/// <summary>
/// 创建文件下载器
/// </summary>
public class FsmCreateDownloader : IFsmNode
{
public string Name { private set; get; } = nameof(FsmCreateDownloader);
void IFsmNode.OnEnter()
{
Debug.Log("创建补丁下载器!");
PatchEventDispatcher.SendPatchStepsChangeMsg(EPatchStates.CreateDownloader);
GameBoot.Instance.StartCoroutine(CreateDownloader());
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
}
IEnumerator CreateDownloader()
{
yield return new WaitForSecondsRealtime(0.5f);
int downloadingMaxNum = 10;
int failedTryAgain = 3;
PatchManager.Downloader = YooAssets.CreatePatchDownloader(downloadingMaxNum, failedTryAgain);
if (PatchManager.Downloader.TotalDownloadCount == 0)
{
Debug.Log("没有发现需要下载的资源");
FsmManager.Transition(nameof(FsmPatchDone));
}
else
{
Debug.Log($"一共发现了{PatchManager.Downloader.TotalDownloadCount}个资源需要更新下载。");
// 发现新更新文件后,挂起流程系统
// 注意:开发者需要在下载前检测磁盘空间不足
int totalDownloadCount = PatchManager.Downloader.TotalDownloadCount;
long totalDownloadBytes = PatchManager.Downloader.TotalDownloadBytes;
PatchEventDispatcher.SendFoundUpdateFilesMsg(totalDownloadCount, totalDownloadBytes);
}
}
}
@@ -1,41 +0,0 @@
using System.Collections;
using UnityEngine;
using YooAsset;
/// <summary>
/// 下载更新文件
/// </summary>
public class FsmDownloadFiles : IFsmNode
{
public string Name { private set; get; } = nameof(FsmDownloadFiles);
void IFsmNode.OnEnter()
{
Debug.Log("开始下载补丁文件!");
PatchEventDispatcher.SendPatchStepsChangeMsg(EPatchStates.DownloadWebFiles);
GameBoot.Instance.StartCoroutine(BeginDownload());
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
}
private IEnumerator BeginDownload()
{
var downloader = PatchManager.Downloader;
// 注册下载回调
downloader.OnDownloadErrorCallback = PatchEventDispatcher.SendWebFileDownloadFailedMsg;
downloader.OnDownloadProgressCallback = PatchEventDispatcher.SendDownloadProgressUpdateMsg;
downloader.BeginDownload();
yield return downloader;
// 检测下载结果
if (downloader.Status != EOperationStatus.Succeed)
yield break;
FsmManager.Transition(nameof(FsmPatchDone));
}
}
@@ -1,24 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 更新完毕
/// </summary>
internal class FsmPatchDone : IFsmNode
{
public string Name { private set; get; } = nameof(FsmPatchDone);
void IFsmNode.OnEnter()
{
Debug.Log("补丁流程更新完毕!");
PatchEventDispatcher.SendPatchStepsChangeMsg(EPatchStates.PatchDone);
FsmManager.Transition(nameof(FsmClearCache));
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
}
}
@@ -1,26 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 初始化工作
/// </summary>
internal class FsmPatchInit : IFsmNode
{
public string Name { private set; get; } = nameof(FsmPatchInit);
void IFsmNode.OnEnter()
{
// 加载更新面板
var go = Resources.Load<GameObject>("PatchWindow");
GameObject.Instantiate(go);
FsmManager.Transition(nameof(FsmUpdateVersion));
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
}
}
@@ -1,23 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 开始游戏
/// </summary>
internal class FsmStartGame : IFsmNode
{
public string Name { private set; get; } = nameof(FsmStartGame);
void IFsmNode.OnEnter()
{
Debug.Log("开始游戏!");
YooAsset.YooAssets.LoadSceneAsync("scene_home");
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 1c01a6c3b0dbdaf43ad5e31634eef386
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,44 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
/// <summary>
/// 更新补丁清单
/// </summary>
public class FsmUpdateManifest : IFsmNode
{
public string Name { private set; get; } = nameof(FsmUpdateManifest);
void IFsmNode.OnEnter()
{
Debug.Log("开始更新资源版本清单!");
PatchEventDispatcher.SendPatchStepsChangeMsg(EPatchStates.UpdateManifest);
GameBoot.Instance.StartCoroutine(UpdateManifest());
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
}
private IEnumerator UpdateManifest()
{
yield return new WaitForSecondsRealtime(0.5f);
var package = YooAssets.GetAssetsPackage("DefaultPackage");
var operation = package.UpdatePackageManifestAsync(PatchManager.PackageVersion, 30);
yield return operation;
if(operation.Status == EOperationStatus.Succeed)
{
FsmManager.Transition(nameof(FsmCreateDownloader));
}
else
{
Debug.LogWarning(operation.Error);
PatchEventDispatcher.SendPatchManifestUpdateFailedMsg();
}
}
}
@@ -1,45 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
/// <summary>
/// 更新资源版本号
/// </summary>
internal class FsmUpdateVersion : IFsmNode
{
public string Name { private set; get; } = nameof(FsmUpdateVersion);
void IFsmNode.OnEnter()
{
Debug.Log("开始获取资源版本号!");
PatchEventDispatcher.SendPatchStepsChangeMsg(EPatchStates.UpdateStaticVersion);
GameBoot.Instance.StartCoroutine(GetStaticVersion());
}
void IFsmNode.OnUpdate()
{
}
void IFsmNode.OnExit()
{
}
private IEnumerator GetStaticVersion()
{
yield return new WaitForSecondsRealtime(0.5f);
var package = YooAssets.GetAssetsPackage("DefaultPackage");
var operation = package.UpdatePackageVersionAsync(30);
yield return operation;
if (operation.Status == EOperationStatus.Succeed)
{
PatchManager.PackageVersion = operation.PackageVersion;
FsmManager.Transition(nameof(FsmUpdateManifest));
}
else
{
Debug.LogWarning(operation.Error);
PatchEventDispatcher.SendStaticVersionUpdateFailedMsg();
}
}
}
@@ -1,54 +0,0 @@
public class PatchEventDefine
{
/// <summary>
/// 补丁流程步骤改变
/// </summary>
public class PatchStatesChange : IEventMessage
{
public EPatchStates CurrentStates;
}
/// <summary>
/// 发现更新文件
/// </summary>
public class FoundUpdateFiles : IEventMessage
{
public int TotalCount;
public long TotalSizeBytes;
}
/// <summary>
/// 下载进度更新
/// </summary>
public class DownloadProgressUpdate : IEventMessage
{
public int TotalDownloadCount;
public int CurrentDownloadCount;
public long TotalDownloadSizeBytes;
public long CurrentDownloadSizeBytes;
}
/// <summary>
/// 资源版本号更新失败
/// </summary>
public class StaticVersionUpdateFailed : IEventMessage
{
}
/// <summary>
/// 补丁清单更新失败
/// </summary>
public class PatchManifestUpdateFailed : IEventMessage
{
}
/// <summary>
/// 网络文件下载失败
/// </summary>
public class WebFileDownloadFailed : IEventMessage
{
public string FileName;
public string Error;
}
}
@@ -1,43 +0,0 @@
public static class PatchEventDispatcher
{
public static void SendPatchStepsChangeMsg(EPatchStates currentStates)
{
PatchEventDefine.PatchStatesChange msg = new PatchEventDefine.PatchStatesChange();
msg.CurrentStates = currentStates;
EventManager.SendMessage(msg);
}
public static void SendFoundUpdateFilesMsg(int totalCount, long totalSizeBytes)
{
PatchEventDefine.FoundUpdateFiles msg = new PatchEventDefine.FoundUpdateFiles();
msg.TotalCount = totalCount;
msg.TotalSizeBytes = totalSizeBytes;
EventManager.SendMessage(msg);
}
public static void SendDownloadProgressUpdateMsg(int totalDownloadCount, int currentDownloadCount, long totalDownloadSizeBytes, long currentDownloadSizeBytes)
{
PatchEventDefine.DownloadProgressUpdate msg = new PatchEventDefine.DownloadProgressUpdate();
msg.TotalDownloadCount = totalDownloadCount;
msg.CurrentDownloadCount = currentDownloadCount;
msg.TotalDownloadSizeBytes = totalDownloadSizeBytes;
msg.CurrentDownloadSizeBytes = currentDownloadSizeBytes;
EventManager.SendMessage(msg);
}
public static void SendStaticVersionUpdateFailedMsg()
{
PatchEventDefine.StaticVersionUpdateFailed msg = new PatchEventDefine.StaticVersionUpdateFailed();
EventManager.SendMessage(msg);
}
public static void SendPatchManifestUpdateFailedMsg()
{
PatchEventDefine.PatchManifestUpdateFailed msg = new PatchEventDefine.PatchManifestUpdateFailed();
EventManager.SendMessage(msg);
}
public static void SendWebFileDownloadFailedMsg(string fileName, string error)
{
PatchEventDefine.WebFileDownloadFailed msg = new PatchEventDefine.WebFileDownloadFailed();
msg.FileName = fileName;
msg.Error = error;
EventManager.SendMessage(msg);
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: fe1971e74e4881641b59485f977219dc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,75 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
public static class PatchManager
{
private static bool _isRun = false;
/// <summary>
/// 下载器
/// </summary>
public static PatchDownloaderOperation Downloader { set; get; }
/// <summary>
/// 包裹的版本信息
/// </summary>
public static string PackageVersion { set; get; }
/// <summary>
/// 开启初始化流程
/// </summary>
public static void Run()
{
if (_isRun == false)
{
_isRun = true;
Debug.Log("开启补丁更新流程...");
// 注意:按照先后顺序添加流程节点
FsmManager.AddNode(new FsmPatchInit());
FsmManager.AddNode(new FsmUpdateVersion());
FsmManager.AddNode(new FsmUpdateManifest());
FsmManager.AddNode(new FsmCreateDownloader());
FsmManager.AddNode(new FsmDownloadFiles());
FsmManager.AddNode(new FsmPatchDone());
FsmManager.AddNode(new FsmClearCache());
FsmManager.AddNode(new FsmStartGame());
FsmManager.Run(nameof(FsmPatchInit));
}
else
{
Debug.LogWarning("补丁更新已经正在进行中!");
}
}
/// <summary>
/// 处理请求操作
/// </summary>
public static void HandleOperation(EPatchOperation operation)
{
if (operation == EPatchOperation.BeginDownloadWebFiles)
{
FsmManager.Transition(nameof(FsmDownloadFiles));
}
else if(operation == EPatchOperation.TryUpdateStaticVersion)
{
FsmManager.Transition(nameof(FsmUpdateVersion));
}
else if (operation == EPatchOperation.TryUpdatePatchManifest)
{
FsmManager.Transition(nameof(FsmUpdateManifest));
}
else if (operation == EPatchOperation.TryDownloadWebFiles)
{
FsmManager.Transition(nameof(FsmCreateDownloader));
}
else
{
throw new NotImplementedException($"{operation}");
}
}
}
@@ -0,0 +1,29 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Window;
[WindowAttribute(100, false)]
public class UIAboutWindow : UIWindow
{
public override void OnCreate()
{
var maskBtn = this.transform.Find("mask").GetComponent<Button>();
maskBtn.onClick.AddListener(OnClicMaskBtn);
}
public override void OnDestroy()
{
}
public override void OnRefresh()
{
}
public override void OnUpdate()
{
}
private void OnClicMaskBtn()
{
UniWindow.CloseWindow<UIAboutWindow>();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8e24fc68d39841044901f3df71616040
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -2,43 +2,51 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using YooAsset;
using UniFramework.Window;
using UniFramework.Event;
public class UIBattleWindow : MonoBehaviour
[WindowAttribute(100, false)]
public class UIBattleWindow : UIWindow
{
private EventGroup _eventGroup = new EventGroup();
private Text _scoreLabel;
private GameObject _overView;
void Awake()
public override void OnCreate()
{
_scoreLabel = this.transform.Find("ScoreView/Score").GetComponent<Text>();
_scoreLabel.text = "Score : 0";
var restartBtn = this.transform.Find("OverView/Restart").GetComponent<Button>();
restartBtn.onClick.AddListener(OnClickLoginBtn);
restartBtn.onClick.AddListener(OnClickRestartBtn);
var homeBtn = this.transform.Find("OverView/Home").GetComponent<Button>();
homeBtn.onClick.AddListener(OnClickHomeBtn);
_overView = this.transform.Find("OverView").gameObject;
_overView.gameObject.SetActive(false);
EventManager.AddListener<BattleEventDefine.ScoreChange>(OnHandleEventMessage);
EventManager.AddListener<BattleEventDefine.GameOver>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.ScoreChange>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.GameOver>(OnHandleEventMessage);
}
void OnDestroy()
public override void OnDestroy()
{
_eventGroup.RemoveAllListener();
}
public override void OnRefresh()
{
_overView.SetActive(false);
}
public override void OnUpdate()
{
EventManager.RemoveListener<BattleEventDefine.ScoreChange > (OnHandleEventMessage);
EventManager.RemoveListener<BattleEventDefine.GameOver>(OnHandleEventMessage);
}
private void OnClickLoginBtn()
private void OnClickRestartBtn()
{
YooAssets.LoadSceneAsync("scene_game");
SceneEventDefine.ChangeToBattleScene.SendEventMessage();
}
private void OnClickHomeBtn()
{
YooAssets.LoadSceneAsync("scene_home");
SceneEventDefine.ChangeToHomeScene.SendEventMessage();
}
private void OnHandleEventMessage(IEventMessage message)
{
@@ -0,0 +1,36 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Window;
[WindowAttribute(100, false)]
public class UIHomeWindow : UIWindow
{
public override void OnCreate()
{
var loginBtn = this.transform.Find("Start").GetComponent<Button>();
loginBtn.onClick.AddListener(OnClickLoginBtn);
var aboutBtn = this.transform.Find("About").GetComponent<Button>();
aboutBtn.onClick.AddListener(OnClicAboutBtn);
}
public override void OnDestroy()
{
}
public override void OnRefresh()
{
}
public override void OnUpdate()
{
}
private void OnClickLoginBtn()
{
SceneEventDefine.ChangeToBattleScene.SendEventMessage();
}
private void OnClicAboutBtn()
{
UniWindow.OpenWindowAsync<UIAboutWindow>("UIAbout");
}
}
@@ -0,0 +1,45 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Window;
[WindowAttribute(1000, true)]
public class UILoadingWindow : UIWindow
{
private Text _info;
private float _timer;
private int _countdown;
public override void OnCreate()
{
_info = this.transform.Find("info").GetComponent<Text>();
}
public override void OnDestroy()
{
}
public override void OnRefresh()
{
_info.text = "Loading";
_timer = 0;
_countdown = 0;
}
public override void OnUpdate()
{
_timer += Time.deltaTime;
if (_timer>= 0.1f)
{
_timer = 0f;
_countdown++;
if (_countdown > 6)
_countdown = 0;
string tips = "Loading";
for(int i=0; i<_countdown; i++)
{
tips += ".";
}
_info.text = tips;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f2bfcc4f450a0b94bb7748fb4788630e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,19 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using YooAsset;
public class UILoginWindow : MonoBehaviour
{
void Awake()
{
var loginBtn = this.transform.Find("Start").GetComponent<Button>();
loginBtn.onClick.AddListener(OnClickLoginBtn);
}
private void OnClickLoginBtn()
{
YooAssets.LoadSceneAsync("scene_game");
}
}