update yooasset2.0

This commit is contained in:
hevinci
2023-09-20 16:10:37 +08:00
parent 01cf9ccd54
commit 6687d75090
253 changed files with 1859 additions and 9299 deletions
@@ -3,6 +3,9 @@ using System.IO;
using System.Text;
using YooAsset;
/// <summary>
/// 文件偏移加密方式
/// </summary>
public class FileOffsetEncryption : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
@@ -15,24 +18,26 @@ public class FileOffsetEncryption : IEncryptionServices
Buffer.BlockCopy(fileData, 0, encryptedData, offset, fileData.Length);
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.LoadFromFileOffset;
result.Encrypted = true;
result.EncryptedData = encryptedData;
return result;
}
else
{
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.Normal;
result.Encrypted = false;
return result;
}
}
}
/// <summary>
/// 文件流加密方式
/// </summary>
public class FileStreamEncryption : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{
// LoadFromStream
if (fileInfo.BundleName.Contains("_gameres_audio"))
{
var fileData = File.ReadAllBytes(fileInfo.FilePath);
@@ -42,15 +47,14 @@ public class FileStreamEncryption : IEncryptionServices
}
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.LoadFromStream;
result.Encrypted = true;
result.EncryptedData = fileData;
return result;
}
// Normal
else
{
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.Normal;
result.Encrypted = false;
return result;
}
}
@@ -2,8 +2,6 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Window;
using UniFramework.Pooling;
using UniFramework.Event;
using UniFramework.Utility;
using YooAsset;
@@ -24,16 +22,14 @@ public class BattleRoom
{
None,
Ready,
Spawn,
SpawnEnemy,
WaitSpawn,
WaitWave,
GameOver,
}
private EventGroup _eventGroup = new EventGroup();
private Spawner _entitySpawner;
private readonly EventGroup _eventGroup = new EventGroup();
private GameObject _roomRoot;
private AssetOperationHandle _musicHandle;
// 关卡参数
private const int EnemyCount = 10;
@@ -49,29 +45,46 @@ public class BattleRoom
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);
private readonly UniTimer _startWaitTimer = UniTimer.CreateOnceTimer(1f);
private readonly UniTimer _spawnWaitTimer = UniTimer.CreateOnceTimer(0.75f);
private readonly UniTimer _waveWaitTimer = UniTimer.CreateOnceTimer(4f);
private readonly List<AssetHandle> _handles = new List<AssetHandle>(1000);
/// <summary>
/// 初始化房间
/// </summary>
public void IntRoom()
{
// 创建房间根对象
_roomRoot = new GameObject("BattleRoom");
// 监听游戏事件
_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>
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>();
foreach(var handle in _handles)
{
handle.Release();
}
_handles.Clear();
}
/// <summary>
@@ -86,30 +99,30 @@ public class BattleRoom
{
if (_startWaitTimer.Update(Time.deltaTime))
{
_steps = ESteps.Spawn;
// 生成实体
var handle = YooAssets.LoadAssetAsync<GameObject>("player_ship");
handle.Completed += (AssetHandle handle) =>
{
handle.InstantiateSync(_roomRoot.transform);
};
_handles.Add(handle);
_steps = ESteps.SpawnEnemy;
}
}
if (_steps == ESteps.Spawn)
if (_steps == ESteps.SpawnEnemy)
{
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 = YooAssets.LoadAssetAsync<GameObject>(enemyLocation);
handle.Completed += (AssetHandle handle) =>
{
// 生成敌人实体
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);
}
handle.InstantiateSync(spawnPosition, spawnRotation, _roomRoot.transform);
};
_handles.Add(handle);
_waveSpawnCount++;
if (_waveSpawnCount >= EnemyCount)
@@ -127,7 +140,7 @@ public class BattleRoom
if (_spawnWaitTimer.Update(Time.deltaTime))
{
_spawnWaitTimer.Reset();
_steps = ESteps.Spawn;
_steps = ESteps.SpawnEnemy;
}
}
@@ -137,62 +150,11 @@ public class BattleRoom
{
_waveWaitTimer.Reset();
_waveSpawnCount = 0;
_steps = ESteps.Spawn;
_steps = ESteps.SpawnEnemy;
}
}
}
/// <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", _roomRoot.transform);
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>
@@ -204,9 +166,12 @@ public class BattleRoom
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);
var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_player");
handle.Completed += (AssetHandle handle) =>
{
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
};
_handles.Add(handle);
_steps = ESteps.GameOver;
BattleEventDefine.GameOver.SendEventMessage();
@@ -216,9 +181,12 @@ public class BattleRoom
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);
var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_enemy");
handle.Completed += (AssetHandle handle) =>
{
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
};
_handles.Add(handle);
_totalScore += EnemyScore;
BattleEventDefine.ScoreChange.SendEventMessage(_totalScore);
@@ -228,9 +196,12 @@ public class BattleRoom
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);
var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_asteroid");
handle.Completed += (AssetHandle handle) =>
{
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
};
_handles.Add(handle);
_totalScore += AsteroidScore;
BattleEventDefine.ScoreChange.SendEventMessage(_totalScore);
@@ -240,18 +211,24 @@ public class BattleRoom
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);
var handle = YooAssets.LoadAssetAsync<GameObject>("player_bullet");
handle.Completed += (AssetHandle handle) =>
{
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
};
_handles.Add(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);
var handle = YooAssets.LoadAssetAsync<GameObject>("enemy_bullet");
handle.Completed += (AssetHandle handle) =>
{
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
};
_handles.Add(handle);
}
}
}
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 2673676235c2ebf4790768011d015d1d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,27 +1,19 @@
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>();
_rigidbody.velocity = this.transform.forward * MoveSpeed;
_rigidbody.angularVelocity = Random.insideUnitSphere * Tumble;
}
void OnTriggerEnter(Collider other)
{
@@ -29,8 +21,7 @@ public class EntityAsteroid : MonoBehaviour
if (name.StartsWith("player"))
{
BattleEventDefine.AsteroidExplosion.SendEventMessage(this.transform.position, this.transform.rotation);
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
void OnTriggerExit(Collider other)
@@ -38,8 +29,7 @@ public class EntityAsteroid : MonoBehaviour
var name = other.gameObject.name;
if (name.StartsWith("Boundary"))
{
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
}
@@ -1,25 +1,18 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Pooling;
public class EntityBullet : MonoBehaviour
{
public float MoveSpeed = 20f;
public float DelayDestroyTime = 5f;
private SpawnHandle _handle;
private Rigidbody _rigidbody;
public void InitEntity(SpawnHandle handle)
{
_handle = handle;
_rigidbody.velocity = this.transform.forward * MoveSpeed;
}
void Awake()
{
_rigidbody = this.transform.GetComponent<Rigidbody>();
_rigidbody.velocity = this.transform.forward * MoveSpeed;
}
void OnTriggerEnter(Collider other)
{
@@ -32,8 +25,7 @@ public class EntityBullet : MonoBehaviour
{
if (name.StartsWith("enemy") == false)
{
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
@@ -41,8 +33,7 @@ public class EntityBullet : MonoBehaviour
{
if (name.StartsWith("player") == false)
{
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
}
@@ -51,8 +42,7 @@ public class EntityBullet : MonoBehaviour
var name = other.gameObject.name;
if (name.StartsWith("Boundary"))
{
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
}
@@ -1,23 +1,16 @@
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)
private void Awake()
{
_handle = handle;
Invoke(nameof(DelayDestroy), DelayDestroyTime);
}
private void DelayDestroy()
{
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
@@ -1,7 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Pooling;
using Random = UnityEngine.Random;
public class EntityEnemy : MonoBehaviour
@@ -17,7 +16,6 @@ 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;
@@ -26,22 +24,18 @@ public class EntityEnemy : MonoBehaviour
private float _targetManeuver;
public void InitEntity(SpawnHandle handle)
{
_handle = handle;
_rigidbody.velocity = this.transform.forward * -5f;
_lastFireTime = Time.time;
_currentSpeed = _rigidbody.velocity.z;
_targetManeuver = 0f;
StartCoroutine(Evade());
}
void Awake()
{
_rigidbody = this.gameObject.GetComponent<Rigidbody>();
_audioSource = this.gameObject.GetComponent<AudioSource>();
_shotSpawn = this.transform.Find("shot_spawn");
_rigidbody.velocity = this.transform.forward * -5f;
_lastFireTime = Time.time;
_currentSpeed = _rigidbody.velocity.z;
_targetManeuver = 0f;
StartCoroutine(Evade());
}
void Update()
{
@@ -72,8 +66,7 @@ public class EntityEnemy : MonoBehaviour
if (name.StartsWith("player"))
{
BattleEventDefine.EnemyDead.SendEventMessage(this.transform.position, this.transform.rotation);
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
void OnTriggerExit(Collider other)
@@ -81,8 +74,7 @@ public class EntityEnemy : MonoBehaviour
var name = other.gameObject.name;
if (name.StartsWith("Boundary"))
{
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
@@ -1,7 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Pooling;
public class EntityPlayer : MonoBehaviour
{
@@ -9,17 +8,11 @@ public class EntityPlayer : MonoBehaviour
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(SpawnHandle handle)
{
_handle = handle;
}
void Awake()
{
_rigidbody = this.gameObject.GetComponent<Rigidbody>();
@@ -58,8 +51,7 @@ public class EntityPlayer : MonoBehaviour
if (name.StartsWith("enemy") || name.StartsWith("asteroid"))
{
BattleEventDefine.PlayerDead.SendEventMessage(this.transform.position, this.transform.rotation);
_handle.Restore();
_handle = null;
GameObject.Destroy(this.gameObject);
}
}
}
@@ -2,7 +2,7 @@
using UnityEngine;
using YooAsset;
public class BhvApplicationQuit : MonoBehaviour
public class ApplicationQuit : MonoBehaviour
{
private void Awake()
{
@@ -1,7 +1,7 @@
using System;
using UnityEngine;
public class BhvBackgroundScroller : MonoBehaviour
public class BackgroundScroller : MonoBehaviour
{
public float ScrollSpeed;
public float TileSizeZ;
@@ -1,6 +1,8 @@
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Event;
using UniFramework.Singleton;
using YooAsset;
public class Boot : MonoBehaviour
@@ -15,23 +17,33 @@ public class Boot : MonoBehaviour
Debug.Log($"资源系统运行模式:{PlayMode}");
Application.targetFrameRate = 60;
Application.runInBackground = true;
DontDestroyOnLoad(this.gameObject);
}
void Start()
IEnumerator Start()
{
// 游戏管理器
GameManager.Instance.Behaviour = this;
// 初始化事件系统
UniEvent.Initalize();
// 初始化单例系统
UniSingleton.Initialize();
// 初始化资源系统
YooAssets.Initialize();
YooAssets.SetOperationSystemMaxTimeSlice(30);
// 创建补丁管理器
UniSingleton.CreateSingleton<PatchManager>();
// 加载更新页面
var go = Resources.Load<GameObject>("PatchWindow");
GameObject.Instantiate(go);
// 开始补丁更新流程
PatchManager.Instance.Run(PlayMode);
PatchOperation operation = new PatchOperation("DefaultPackage", DefaultBuildPipeline.BuiltinBuildPipelineName, PlayMode);
YooAssets.StartOperation(operation);
yield return operation;
// 设置默认的资源包
var gamePackage = YooAssets.GetPackage("DefaultPackage");
YooAssets.SetDefaultPackage(gamePackage);
// 切换到主页面场景
SceneEventDefine.ChangeToHomeScene.SendEventMessage();
}
}
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: beab7f759234b61469afb94f517f959b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,45 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Pooling;
using UniFramework.Window;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
internal class FsmInitGame : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
UniSingleton.StartCoroutine(Prepare());
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
private IEnumerator Prepare()
{
var handle = YooAssets.LoadAssetAsync<GameObject>("UICanvas");
yield return handle;
var canvas = handle.InstantiateSync();
var desktop = canvas.transform.Find("Desktop").gameObject;
GameObject.DontDestroyOnLoad(canvas);
// 初始化窗口系统
UniWindow.Initalize(desktop);
// 初始化对象池系统
UniPooling.Initalize();
_machine.ChangeState<FsmSceneHome>();
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 35d459ebb0d7dc947b7b62d1f64a412f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,47 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Window;
using UniFramework.Event;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
internal class FsmSceneBattle : IStateNode
{
private BattleRoom _battleRoom;
void IStateNode.OnCreate(StateMachine machine)
{
}
void IStateNode.OnEnter()
{
UniSingleton.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();
// 释放资源
var package = YooAssets.GetPackage("DefaultPackage");
package.UnloadUnusedAssets();
}
}
@@ -1,38 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Window;
using UniFramework.Singleton;
using YooAsset;
internal class FsmSceneHome : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
UniSingleton.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");
// 释放资源
var package = YooAssets.GetPackage("DefaultPackage");
package.UnloadUnusedAssets();
}
}
@@ -2,63 +2,56 @@
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Event;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
public class GameManager : SingletonInstance<GameManager>, ISingleton
public class GameManager
{
private bool _isRun = false;
private EventGroup _eventGroup = new EventGroup();
private StateMachine _machine;
void ISingleton.OnCreate(object createParam)
private static GameManager _instance;
public static GameManager Instance
{
}
void ISingleton.OnDestroy()
{
_eventGroup.RemoveAllListener();
}
void ISingleton.OnUpdate()
{
if (_machine != null)
_machine.Update();
}
public void Run()
{
if (_isRun == false)
get
{
_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("补丁更新已经正在进行中!");
if (_instance == null)
_instance = new GameManager();
return _instance;
}
}
private readonly EventGroup _eventGroup = new EventGroup();
/// <summary>
/// 协程启动器
/// </summary>
public MonoBehaviour Behaviour;
private GameManager()
{
// 注册监听事件
_eventGroup.AddListener<SceneEventDefine.ChangeToHomeScene>(OnHandleEventMessage);
_eventGroup.AddListener<SceneEventDefine.ChangeToBattleScene>(OnHandleEventMessage);
}
/// <summary>
/// 开启一个协程
/// </summary>
public void StartCoroutine(IEnumerator enumerator)
{
Behaviour.StartCoroutine(enumerator);
}
/// <summary>
/// 接收事件
/// </summary>
private void OnHandleEventMessage(IEventMessage message)
{
if(message is SceneEventDefine.ChangeToHomeScene)
if (message is SceneEventDefine.ChangeToHomeScene)
{
_machine.ChangeState<FsmSceneHome>();
YooAssets.LoadSceneAsync("scene_home");
}
else if(message is SceneEventDefine.ChangeToBattleScene)
else if (message is SceneEventDefine.ChangeToBattleScene)
{
_machine.ChangeState<FsmSceneBattle>();
YooAssets.LoadSceneAsync("scene_battle");
}
}
}
@@ -0,0 +1,67 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Event;
using UniFramework.Machine;
using YooAsset;
internal class SceneBattle : MonoBehaviour
{
public GameObject CanvasDesktop;
private AssetHandle _windowHandle;
private AssetHandle _musicHandle;
private BattleRoom _battleRoom;
private IEnumerator Start()
{
// 加载战斗页面
_windowHandle = YooAssets.LoadAssetAsync<GameObject>("UIBattle");
yield return _windowHandle;
_windowHandle.InstantiateSync(CanvasDesktop.transform);
// 加载背景音乐
var package = YooAssets.GetPackage("DefaultPackage");
_musicHandle = package.LoadAssetAsync<AudioClip>("music_background");
yield return _musicHandle;
// 播放背景音乐
var audioSource = this.gameObject.AddComponent<AudioSource>();
audioSource.loop = true;
audioSource.clip = _musicHandle.AssetObject as AudioClip;
audioSource.Play();
_battleRoom = new BattleRoom();
_battleRoom.IntRoom();
}
private void OnDestroy()
{
if (_windowHandle != null)
{
_windowHandle.Release();
_windowHandle = null;
}
if (_musicHandle != null)
{
_musicHandle.Release();
_musicHandle = null;
}
if (_battleRoom != null)
{
_battleRoom.DestroyRoom();
_battleRoom = null;
}
// 切换场景的时候释放资源
var package = YooAssets.GetPackage("DefaultPackage");
package.UnloadUnusedAssets();
}
private void Update()
{
if (_battleRoom != null)
_battleRoom.UpdateRoom();
}
}
@@ -0,0 +1,31 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YooAsset;
public class SceneHome : MonoBehaviour
{
public GameObject CanvasDesktop;
private AssetHandle _windowHandle;
private IEnumerator Start()
{
// 加载登录页面
_windowHandle = YooAssets.LoadAssetAsync<GameObject>("UIHome");
yield return _windowHandle;
_windowHandle.InstantiateSync(CanvasDesktop.transform);
}
private void OnDestroy()
{
if (_windowHandle != null)
{
_windowHandle.Release();
_windowHandle = null;
}
// 切换场景的时候释放资源
var package = YooAssets.GetPackage("DefaultPackage");
package.UnloadUnusedAssets();
}
}
@@ -1,27 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class BundleStream : FileStream
{
public const byte KEY = 64;
public BundleStream(string path, FileMode mode, FileAccess access, FileShare share) : base(path, mode, access, share)
{
}
public BundleStream(string path, FileMode mode) : base(path, mode)
{
}
public override int Read(byte[] array, int offset, int count)
{
var index = base.Read(array, offset, count);
for (int i = 0; i < array.Length; i++)
{
array[i] ^= KEY;
}
return index;
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 7da6bc93686626a4cb248691891073ac
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -2,11 +2,12 @@
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using YooAsset;
/// <summary>
/// 清理未使用的缓存文件
/// </summary>
internal class FsmClearCache : IStateNode
internal class FsmClearPackageCache : IStateNode
{
private StateMachine _machine;
@@ -17,7 +18,8 @@ internal class FsmClearCache : IStateNode
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("清理未使用的缓存文件!");
var package = YooAsset.YooAssets.GetPackage("DefaultPackage");
var packageName = (string)_machine.GetBlackboardValue("PackageName");
var package = YooAssets.GetPackage(packageName);
var operation = package.ClearUnusedCacheFilesAsync();
operation.Completed += Operation_Completed;
}
@@ -30,6 +32,6 @@ internal class FsmClearCache : IStateNode
private void Operation_Completed(YooAsset.AsyncOperationBase obj)
{
_machine.ChangeState<FsmPatchDone>();
_machine.ChangeState<FsmUpdaterDone>();
}
}
@@ -2,13 +2,12 @@
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
/// <summary>
/// 创建文件下载器
/// </summary>
public class FsmCreateDownloader : IStateNode
public class FsmCreatePackageDownloader : IStateNode
{
private StateMachine _machine;
@@ -19,7 +18,7 @@ public class FsmCreateDownloader : IStateNode
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("创建补丁下载器!");
UniSingleton.StartCoroutine(CreateDownloader());
GameManager.Instance.StartCoroutine(CreateDownloader());
}
void IStateNode.OnUpdate()
{
@@ -32,21 +31,20 @@ public class FsmCreateDownloader : IStateNode
{
yield return new WaitForSecondsRealtime(0.5f);
var packageName = (string)_machine.GetBlackboardValue("PackageName");
var package = YooAssets.GetPackage(packageName);
int downloadingMaxNum = 10;
int failedTryAgain = 3;
var downloader = YooAssets.CreateResourceDownloader(downloadingMaxNum, failedTryAgain);
PatchManager.Instance.Downloader = downloader;
var downloader = package.CreateResourceDownloader(downloadingMaxNum, failedTryAgain);
_machine.SetBlackboardValue("Downloader", downloader);
if (downloader.TotalDownloadCount == 0)
{
Debug.Log("Not found any download files !");
_machine.ChangeState<FsmDownloadOver>();
_machine.ChangeState<FsmUpdaterDone>();
}
else
{
//A total of 10 files were found that need to be downloaded
Debug.Log($"Found total {downloader.TotalDownloadCount} files that need download !");
// 发现新更新文件后,挂起流程系统
// 注意:开发者需要在下载前检测磁盘空间不足
int totalDownloadCount = downloader.TotalDownloadCount;
@@ -1,13 +1,12 @@
using System.Collections;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
/// <summary>
/// 下载更新文件
/// </summary>
public class FsmDownloadFiles : IStateNode
public class FsmDownloadPackageFiles : IStateNode
{
private StateMachine _machine;
@@ -18,7 +17,7 @@ public class FsmDownloadFiles : IStateNode
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("开始下载补丁文件!");
UniSingleton.StartCoroutine(BeginDownload());
GameManager.Instance.StartCoroutine(BeginDownload());
}
void IStateNode.OnUpdate()
{
@@ -29,9 +28,7 @@ public class FsmDownloadFiles : IStateNode
private IEnumerator BeginDownload()
{
var downloader = PatchManager.Instance.Downloader;
// 注册下载回调
var downloader = (ResourceDownloaderOperation)_machine.GetBlackboardValue("Downloader");
downloader.OnDownloadErrorCallback = PatchEventDefine.WebFileDownloadFailed.SendEventMessage;
downloader.OnDownloadProgressCallback = PatchEventDefine.DownloadProgressUpdate.SendEventMessage;
downloader.BeginDownload();
@@ -41,6 +38,6 @@ public class FsmDownloadFiles : IStateNode
if (downloader.Status != EOperationStatus.Succeed)
yield break;
_machine.ChangeState<FsmPatchDone>();
_machine.ChangeState<FsmDownloadPackageOver>();
}
}
@@ -6,7 +6,7 @@ using UniFramework.Machine;
/// <summary>
/// 下载完毕
/// </summary>
internal class FsmDownloadOver : IStateNode
internal class FsmDownloadPackageOver : IStateNode
{
private StateMachine _machine;
@@ -16,7 +16,7 @@ internal class FsmDownloadOver : IStateNode
}
void IStateNode.OnEnter()
{
_machine.ChangeState<FsmClearCache>();
_machine.ChangeState<FsmClearPackageCache>();
}
void IStateNode.OnUpdate()
{
@@ -4,13 +4,12 @@ using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
/// <summary>
/// 初始化资源包
/// </summary>
internal class FsmInitialize : IStateNode
internal class FsmInitializePackage : IStateNode
{
private StateMachine _machine;
@@ -21,7 +20,7 @@ internal class FsmInitialize : IStateNode
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("初始化资源包!");
UniSingleton.StartCoroutine(InitPackage());
GameManager.Instance.StartCoroutine(InitPackage());
}
void IStateNode.OnUpdate()
{
@@ -32,25 +31,21 @@ internal class FsmInitialize : IStateNode
private IEnumerator InitPackage()
{
yield return new WaitForSeconds(1f);
var playMode = (EPlayMode)_machine.GetBlackboardValue("PlayMode");
var packageName = (string)_machine.GetBlackboardValue("PackageName");
var buildPipeline = (string)_machine.GetBlackboardValue("BuildPipeline");
var playMode = PatchManager.Instance.PlayMode;
// 创建默认的资源包
string packageName = "DefaultPackage";
// 创建资源包裹类
var package = YooAssets.TryGetPackage(packageName);
if (package == null)
{
package = YooAssets.CreatePackage(packageName);
YooAssets.SetDefaultPackage(package);
}
// 编辑器下的模拟模式
InitializationOperation initializationOperation = null;
if (playMode == EPlayMode.EditorSimulateMode)
{
var createParameters = new EditorSimulateModeParameters();
createParameters.SimulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild(packageName);
createParameters.SimulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild(buildPipeline, packageName);
initializationOperation = package.InitializeAsync(createParameters);
}
@@ -58,7 +53,7 @@ internal class FsmInitialize : IStateNode
if (playMode == EPlayMode.OfflinePlayMode)
{
var createParameters = new OfflinePlayModeParameters();
createParameters.DecryptionServices = new GameDecryptionServices();
createParameters.DecryptionServices = new FileStreamDecryption();
initializationOperation = package.InitializeAsync(createParameters);
}
@@ -68,9 +63,8 @@ internal class FsmInitialize : IStateNode
string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL();
var createParameters = new HostPlayModeParameters();
createParameters.DecryptionServices = new GameDecryptionServices();
createParameters.DecryptionServices = new FileStreamDecryption();
createParameters.BuildinQueryServices = new GameQueryServices();
createParameters.DeliveryQueryServices = new DefaultDeliveryQueryServices();
createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
initializationOperation = package.InitializeAsync(createParameters);
}
@@ -81,22 +75,24 @@ internal class FsmInitialize : IStateNode
string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL();
var createParameters = new WebPlayModeParameters();
createParameters.DecryptionServices = new GameDecryptionServices();
createParameters.DecryptionServices = new FileStreamDecryption();
createParameters.BuildinQueryServices = new GameQueryServices();
createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
initializationOperation = package.InitializeAsync(createParameters);
}
yield return initializationOperation;
if (initializationOperation.Status == EOperationStatus.Succeed)
{
_machine.ChangeState<FsmUpdateVersion>();
}
else
// 如果初始化失败弹出提示界面
if (initializationOperation.Status != EOperationStatus.Succeed)
{
Debug.LogWarning($"{initializationOperation.Error}");
PatchEventDefine.InitializeFailed.SendEventMessage();
}
else
{
_machine.ChangeState<FsmUpdatePackageVersion>();
}
}
/// <summary>
@@ -129,7 +125,6 @@ internal class FsmInitialize : IStateNode
#endif
}
/// <summary>
/// 远端资源地址查询服务类
/// </summary>
@@ -154,44 +149,91 @@ internal class FsmInitialize : IStateNode
}
/// <summary>
/// 资源文件解密服务类
/// 资源文件流加载解密类
/// </summary>
private class GameDecryptionServices : IDecryptionServices
private class FileStreamDecryption : IDecryptionServices
{
public ulong LoadFromFileOffset(DecryptFileInfo fileInfo)
/// <summary>
/// 同步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary>
AssetBundle IDecryptionServices.LoadAssetBundle(DecryptFileInfo fileInfo, out Stream managedStream)
{
return 32;
BundleStream bundleStream = new BundleStream(fileInfo.FileLoadPath, FileMode.Open, FileAccess.Read, FileShare.Read);
managedStream = bundleStream;
return AssetBundle.LoadFromStream(bundleStream, fileInfo.ConentCRC, GetManagedReadBufferSize());
}
public byte[] LoadFromMemory(DecryptFileInfo fileInfo)
/// <summary>
/// 异步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary>
AssetBundleCreateRequest IDecryptionServices.LoadAssetBundleAsync(DecryptFileInfo fileInfo, out Stream managedStream)
{
throw new NotImplementedException();
BundleStream bundleStream = new BundleStream(fileInfo.FileLoadPath, FileMode.Open, FileAccess.Read, FileShare.Read);
managedStream = bundleStream;
return AssetBundle.LoadFromStreamAsync(bundleStream, fileInfo.ConentCRC, GetManagedReadBufferSize());
}
public Stream LoadFromStream(DecryptFileInfo fileInfo)
{
BundleStream bundleStream = new BundleStream(fileInfo.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
return bundleStream;
}
public uint GetManagedReadBufferSize()
private static uint GetManagedReadBufferSize()
{
return 1024;
}
}
/// <summary>
/// 默认的分发资源查询服务类
/// 资源文件偏移加载解密类
/// </summary>
private class DefaultDeliveryQueryServices : IDeliveryQueryServices
private class FileOffsetDecryption : IDecryptionServices
{
public DeliveryFileInfo GetDeliveryFileInfo(string packageName, string fileName)
/// <summary>
/// 同步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary>
AssetBundle IDecryptionServices.LoadAssetBundle(DecryptFileInfo fileInfo, out Stream managedStream)
{
throw new NotImplementedException();
managedStream = null;
return AssetBundle.LoadFromFile(fileInfo.FileLoadPath, fileInfo.ConentCRC, GetFileOffset());
}
public bool QueryDeliveryFiles(string packageName, string fileName)
/// <summary>
/// 异步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary>
AssetBundleCreateRequest IDecryptionServices.LoadAssetBundleAsync(DecryptFileInfo fileInfo, out Stream managedStream)
{
return false;
managedStream = null;
return AssetBundle.LoadFromFileAsync(fileInfo.FileLoadPath, fileInfo.ConentCRC, GetFileOffset());
}
private static ulong GetFileOffset()
{
return 32;
}
}
}
/// <summary>
/// 资源文件解密流
/// </summary>
public class BundleStream : FileStream
{
public const byte KEY = 64;
public BundleStream(string path, FileMode mode, FileAccess access, FileShare share) : base(path, mode, access, share)
{
}
public BundleStream(string path, FileMode mode) : base(path, mode)
{
}
public override int Read(byte[] array, int offset, int count)
{
var index = base.Read(array, offset, count);
for (int i = 0; i < array.Length; i++)
{
array[i] ^= KEY;
}
return index;
}
}
@@ -1,34 +0,0 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Singleton;
/// <summary>
/// 流程准备工作
/// </summary>
internal class FsmPatchPrepare : IStateNode
{
private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine)
{
_machine = machine;
}
void IStateNode.OnEnter()
{
// 加载更新面板
var go = Resources.Load<GameObject>("PatchWindow");
GameObject.Instantiate(go);
_machine.ChangeState<FsmInitialize>();
}
void IStateNode.OnUpdate()
{
}
void IStateNode.OnExit()
{
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b4b6ef49759dcf14d80c5aa2d360f597
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -2,13 +2,12 @@
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
/// <summary>
/// 更新资源清单
/// </summary>
public class FsmUpdateManifest : IStateNode
public class FsmUpdatePackageManifest : IStateNode
{
private StateMachine _machine;
@@ -19,7 +18,7 @@ public class FsmUpdateManifest : IStateNode
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("更新资源清单!");
UniSingleton.StartCoroutine(UpdateManifest());
GameManager.Instance.StartCoroutine(UpdateManifest());
}
void IStateNode.OnUpdate()
{
@@ -32,19 +31,22 @@ public class FsmUpdateManifest : IStateNode
{
yield return new WaitForSecondsRealtime(0.5f);
var packageName = (string)_machine.GetBlackboardValue("PackageName");
var packageVersion = (string)_machine.GetBlackboardValue("PackageVersion");
var package = YooAssets.GetPackage(packageName);
bool savePackageVersion = true;
var package = YooAssets.GetPackage("DefaultPackage");
var operation = package.UpdatePackageManifestAsync(PatchManager.Instance.PackageVersion, savePackageVersion);
var operation = package.UpdatePackageManifestAsync(packageVersion, savePackageVersion);
yield return operation;
if(operation.Status == EOperationStatus.Succeed)
{
_machine.ChangeState<FsmCreateDownloader>();
}
else
if (operation.Status != EOperationStatus.Succeed)
{
Debug.LogWarning(operation.Error);
PatchEventDefine.PatchManifestUpdateFailed.SendEventMessage();
yield break;
}
else
{
_machine.ChangeState<FsmCreatePackageDownloader>();
}
}
}
@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 8998f67b4187d404eb26190f5cd5ac86
guid: 13faaa12de67f5e4db31cd8a44563089
MonoImporter:
externalObjects: {}
serializedVersion: 2
@@ -2,13 +2,12 @@
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Singleton;
using YooAsset;
/// <summary>
/// 更新资源版本号
/// </summary>
internal class FsmUpdateVersion : IStateNode
internal class FsmUpdatePackageVersion : IStateNode
{
private StateMachine _machine;
@@ -19,7 +18,7 @@ internal class FsmUpdateVersion : IStateNode
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("获取最新的资源版本 !");
UniSingleton.StartCoroutine(GetStaticVersion());
GameManager.Instance.StartCoroutine(UpdatePackageVersion());
}
void IStateNode.OnUpdate()
{
@@ -28,24 +27,24 @@ internal class FsmUpdateVersion : IStateNode
{
}
private IEnumerator GetStaticVersion()
private IEnumerator UpdatePackageVersion()
{
yield return new WaitForSecondsRealtime(0.5f);
var package = YooAssets.GetPackage("DefaultPackage");
var packageName = (string)_machine.GetBlackboardValue("PackageName");
var package = YooAssets.GetPackage(packageName);
var operation = package.UpdatePackageVersionAsync();
yield return operation;
if (operation.Status == EOperationStatus.Succeed)
{
PatchManager.Instance.PackageVersion = operation.PackageVersion;
Debug.Log($"远端最新版本为: {operation.PackageVersion}");
_machine.ChangeState<FsmUpdateManifest>();
}
else
if (operation.Status != EOperationStatus.Succeed)
{
Debug.LogWarning(operation.Error);
PatchEventDefine.PackageVersionUpdateFailed.SendEventMessage();
}
else
{
_machine.SetBlackboardValue("PackageVersion", operation.PackageVersion);
_machine.ChangeState<FsmUpdatePackageManifest>();
}
}
}
@@ -2,25 +2,17 @@
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Singleton;
/// <summary>
/// 流程更新完毕
/// </summary>
internal class FsmPatchDone : IStateNode
internal class FsmUpdaterDone : IStateNode
{
void IStateNode.OnCreate(StateMachine machine)
{
}
void IStateNode.OnEnter()
{
PatchEventDefine.PatchStatesChange.SendEventMessage("开始游戏!");
// 创建游戏管理器
UniSingleton.CreateSingleton<GameManager>();
// 开启游戏流程
GameManager.Instance.Run();
}
void IStateNode.OnUpdate()
{
@@ -1,111 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Event;
using UniFramework.Singleton;
using YooAsset;
public class PatchManager : SingletonInstance<PatchManager>, ISingleton
{
/// <summary>
/// 运行模式
/// </summary>
public EPlayMode PlayMode { private set; get; }
/// <summary>
/// 包裹的版本信息
/// </summary>
public string PackageVersion { set; get; }
/// <summary>
/// 下载器
/// </summary>
public ResourceDownloaderOperation Downloader { set; get; }
private bool _isRun = false;
private EventGroup _eventGroup = new EventGroup();
private StateMachine _machine;
void ISingleton.OnCreate(object createParam)
{
}
void ISingleton.OnDestroy()
{
_eventGroup.RemoveAllListener();
}
void ISingleton.OnUpdate()
{
if (_machine != null)
_machine.Update();
}
/// <summary>
/// 开启流程
/// </summary>
public void Run(EPlayMode playMode)
{
if (_isRun == false)
{
_isRun = true;
PlayMode = playMode;
// 注册监听事件
_eventGroup.AddListener<UserEventDefine.UserTryInitialize>(OnHandleEventMessage);
_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<FsmPatchPrepare>();
_machine.AddNode<FsmInitialize>();
_machine.AddNode<FsmUpdateVersion>();
_machine.AddNode<FsmUpdateManifest>();
_machine.AddNode<FsmCreateDownloader>();
_machine.AddNode<FsmDownloadFiles>();
_machine.AddNode<FsmDownloadOver>();
_machine.AddNode<FsmClearCache>();
_machine.AddNode<FsmPatchDone>();
_machine.Run<FsmPatchPrepare>();
}
else
{
Debug.LogWarning("补丁更新已经正在进行中!");
}
}
/// <summary>
/// 接收事件
/// </summary>
private void OnHandleEventMessage(IEventMessage message)
{
if (message is UserEventDefine.UserTryInitialize)
{
_machine.ChangeState<FsmInitialize>();
}
else 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()}");
}
}
}
@@ -0,0 +1,98 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniFramework.Machine;
using UniFramework.Event;
using YooAsset;
public class PatchOperation : GameAsyncOperation
{
private enum ESteps
{
None,
Update,
Done,
}
private readonly EventGroup _eventGroup = new EventGroup();
private readonly StateMachine _machine;
private ESteps _steps = ESteps.None;
public PatchOperation(string packageName, string buildPipeline, EPlayMode playMode)
{
// 注册监听事件
_eventGroup.AddListener<UserEventDefine.UserTryInitialize>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserBeginDownloadWebFiles>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryUpdatePackageVersion>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryUpdatePatchManifest>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryDownloadWebFiles>(OnHandleEventMessage);
// 创建状态机
_machine = new StateMachine(this);
_machine.AddNode<FsmInitializePackage>();
_machine.AddNode<FsmUpdatePackageVersion>();
_machine.AddNode<FsmUpdatePackageManifest>();
_machine.AddNode<FsmCreatePackageDownloader>();
_machine.AddNode<FsmDownloadPackageFiles>();
_machine.AddNode<FsmDownloadPackageOver>();
_machine.AddNode<FsmClearPackageCache>();
_machine.AddNode<FsmUpdaterDone>();
_machine.SetBlackboardValue("PackageName", packageName);
_machine.SetBlackboardValue("PlayMode", playMode);
_machine.SetBlackboardValue("BuildPipeline", buildPipeline);
}
protected override void OnStart()
{
_steps = ESteps.Update;
_machine.Run<FsmInitializePackage>();
}
protected override void OnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if(_steps == ESteps.Update)
{
_machine.Update();
if(_machine.CurrentNode == typeof(FsmUpdaterDone).FullName)
{
_eventGroup.RemoveAllListener();
Status = EOperationStatus.Succeed;
_steps = ESteps.Done;
}
}
}
/// <summary>
/// 接收事件
/// </summary>
private void OnHandleEventMessage(IEventMessage message)
{
if (message is UserEventDefine.UserTryInitialize)
{
_machine.ChangeState<FsmInitializePackage>();
}
else if (message is UserEventDefine.UserBeginDownloadWebFiles)
{
_machine.ChangeState<FsmDownloadPackageFiles>();
}
else if (message is UserEventDefine.UserTryUpdatePackageVersion)
{
_machine.ChangeState<FsmUpdatePackageVersion>();
}
else if (message is UserEventDefine.UserTryUpdatePatchManifest)
{
_machine.ChangeState<FsmUpdatePackageManifest>();
}
else if (message is UserEventDefine.UserTryDownloadWebFiles)
{
_machine.ChangeState<FsmCreatePackageDownloader>();
}
else
{
throw new System.NotImplementedException($"{message.GetType()}");
}
}
}
@@ -1,43 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Window;
using YooAsset;
[WindowAttribute(100, false)]
public class UIAboutWindow : UIWindow
{
private Text _info;
private RawFileOperationHandle _handle;
public override void OnCreate()
{
var maskBtn = this.transform.Find("mask").GetComponent<Button>();
maskBtn.onClick.AddListener(OnClicMaskBtn);
_info = this.transform.Find("bg/info").GetComponent<Text>();
_handle = YooAssets.LoadRawFileAsync("about");
_handle.Completed += _handle_Completed;
}
public override void OnDestroy()
{
_handle.Release();
}
public override void OnRefresh()
{
}
public override void OnUpdate()
{
}
private void _handle_Completed(RawFileOperationHandle obj)
{
_info.text = _handle.GetRawFileText();
}
private void OnClicMaskBtn()
{
UniWindow.CloseWindow<UIAboutWindow>();
}
}
@@ -0,0 +1,18 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIAboutWindow : MonoBehaviour
{
private void Awake()
{
var maskBtn = this.transform.Find("mask").GetComponent<Button>();
maskBtn.onClick.AddListener(OnClicMaskBtn);
}
private void OnClicMaskBtn()
{
GameObject.Destroy(this.gameObject);
}
}
@@ -2,18 +2,17 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Window;
using UniFramework.Event;
[WindowAttribute(100, false)]
public class UIBattleWindow : UIWindow
public class UIBattleWindow : MonoBehaviour
{
private EventGroup _eventGroup = new EventGroup();
private Text _scoreLabel;
private readonly EventGroup _eventGroup = new EventGroup();
private GameObject _overView;
private Text _scoreLabel;
public override void OnCreate()
private void Awake()
{
_overView = this.transform.Find("OverView").gameObject;
_scoreLabel = this.transform.Find("ScoreView/Score").GetComponent<Text>();
_scoreLabel.text = "Score : 0";
@@ -23,22 +22,13 @@ public class UIBattleWindow : UIWindow
var homeBtn = this.transform.Find("OverView/Home").GetComponent<Button>();
homeBtn.onClick.AddListener(OnClickHomeBtn);
_overView = this.transform.Find("OverView").gameObject;
_eventGroup.AddListener<BattleEventDefine.ScoreChange>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.GameOver>(OnHandleEventMessage);
}
public override void OnDestroy()
private void OnDestroy()
{
_eventGroup.RemoveAllListener();
}
public override void OnRefresh()
{
_overView.SetActive(false);
}
public override void OnUpdate()
{
}
private void OnClickRestartBtn()
{
@@ -2,34 +2,32 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Window;
[WindowAttribute(100, false)]
public class UIHomeWindow : UIWindow
public class UIHomeWindow : MonoBehaviour
{
private Text _version;
private GameObject _aboutView;
public override void OnCreate()
private void Awake()
{
_version = this.transform.Find("version").GetComponent<Text>();
_aboutView = this.transform.Find("AboutView").gameObject;
var loginBtn = this.transform.Find("Start").GetComponent<Button>();
loginBtn.onClick.AddListener(OnClickLoginBtn);
var aboutBtn = this.transform.Find("About").GetComponent<Button>();
aboutBtn.onClick.AddListener(OnClicAboutBtn);
var maskBtn = this.transform.Find("AboutView/mask").GetComponent<Button>();
maskBtn.onClick.AddListener(OnClickMaskBtn);
}
public override void OnDestroy()
{
}
public override void OnRefresh()
private void Start()
{
var package = YooAsset.YooAssets.GetPackage("DefaultPackage");
_version.text = "Ver : " + package.GetPackageVersion();
}
public override void OnUpdate()
{
}
private void OnClickLoginBtn()
{
@@ -37,6 +35,10 @@ public class UIHomeWindow : UIWindow
}
private void OnClicAboutBtn()
{
UniWindow.OpenWindowAsync<UIAboutWindow>("UIAbout");
_aboutView.SetActive(true);
}
private void OnClickMaskBtn()
{
_aboutView.SetActive(false);
}
}
@@ -2,30 +2,25 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniFramework.Window;
using UniFramework.Utility;
[WindowAttribute(1000, true)]
public class UILoadingWindow : UIWindow
public class UILoadingWindow : MonoBehaviour
{
private Text _info;
private int _countdown;
private UniTimer _timer = UniTimer.CreatePepeatTimer(0, 0.2f);
public override void OnCreate()
private void Awake()
{
_info = this.transform.Find("info").GetComponent<Text>();
}
public override void OnDestroy()
{
}
public override void OnRefresh()
private void Start()
{
_info.text = "Loading";
_timer.Reset();
_countdown = 0;
}
public override void OnUpdate()
private void Update()
{
if(_timer.Update(Time.deltaTime))
{