style : Code text indent format

pull/229/head
hevinci 2023-12-21 19:49:50 +08:00
parent 552d689317
commit 2332765932
43 changed files with 2463 additions and 2463 deletions

View File

@ -8,43 +8,43 @@ using YooAsset.Editor;
[DisplayName("打包特效纹理(自定义)")] [DisplayName("打包特效纹理(自定义)")]
public class PackEffectTexture : IPackRule public class PackEffectTexture : IPackRule
{ {
private const string PackDirectory = "Assets/Effect/Textures/"; private const string PackDirectory = "Assets/Effect/Textures/";
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data) PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{ {
string assetPath = data.AssetPath; string assetPath = data.AssetPath;
if (assetPath.StartsWith(PackDirectory) == false) if (assetPath.StartsWith(PackDirectory) == false)
throw new Exception($"Only support folder : {PackDirectory}"); throw new Exception($"Only support folder : {PackDirectory}");
string assetName = Path.GetFileName(assetPath).ToLower(); string assetName = Path.GetFileName(assetPath).ToLower();
string firstChar = assetName.Substring(0, 1); string firstChar = assetName.Substring(0, 1);
string bundleName = $"{PackDirectory}effect_texture_{firstChar}"; string bundleName = $"{PackDirectory}effect_texture_{firstChar}";
var packRuleResult = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension); var packRuleResult = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return packRuleResult; return packRuleResult;
} }
} }
[DisplayName("打包视频(自定义)")] [DisplayName("打包视频(自定义)")]
public class PackVideo : IPackRule public class PackVideo : IPackRule
{ {
public PackRuleResult GetPackRuleResult(PackRuleData data) public PackRuleResult GetPackRuleResult(PackRuleData data)
{ {
string bundleName = RemoveExtension(data.AssetPath); string bundleName = RemoveExtension(data.AssetPath);
string fileExtension = Path.GetExtension(data.AssetPath); string fileExtension = Path.GetExtension(data.AssetPath);
fileExtension = fileExtension.Remove(0, 1); fileExtension = fileExtension.Remove(0, 1);
PackRuleResult result = new PackRuleResult(bundleName, fileExtension); PackRuleResult result = new PackRuleResult(bundleName, fileExtension);
return result; return result;
} }
private string RemoveExtension(string str) private string RemoveExtension(string str)
{ {
if (string.IsNullOrEmpty(str)) if (string.IsNullOrEmpty(str))
return str; return str;
int index = str.LastIndexOf("."); int index = str.LastIndexOf(".");
if (index == -1) if (index == -1)
return str; return str;
else else
return str.Remove(index); //"assets/config/test.unity3d" --> "assets/config/test" return str.Remove(index); //"assets/config/test.unity3d" --> "assets/config/test"
} }
} }

View File

@ -6,133 +6,133 @@ using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class PackageComparatorWindow : EditorWindow public class PackageComparatorWindow : EditorWindow
{ {
static PackageComparatorWindow _thisInstance; static PackageComparatorWindow _thisInstance;
[MenuItem("Tools/补丁包比对工具", false, 102)] [MenuItem("Tools/补丁包比对工具", false, 102)]
static void ShowWindow() static void ShowWindow()
{ {
if (_thisInstance == null) if (_thisInstance == null)
{ {
_thisInstance = EditorWindow.GetWindow(typeof(PackageComparatorWindow), false, "补丁包比对工具", true) as PackageComparatorWindow; _thisInstance = EditorWindow.GetWindow(typeof(PackageComparatorWindow), false, "补丁包比对工具", true) as PackageComparatorWindow;
_thisInstance.minSize = new Vector2(800, 600); _thisInstance.minSize = new Vector2(800, 600);
} }
_thisInstance.Show(); _thisInstance.Show();
} }
private string _manifestPath1 = string.Empty; private string _manifestPath1 = string.Empty;
private string _manifestPath2 = string.Empty; private string _manifestPath2 = string.Empty;
private readonly List<PackageBundle> _changeList = new List<PackageBundle>(); private readonly List<PackageBundle> _changeList = new List<PackageBundle>();
private readonly List<PackageBundle> _newList = new List<PackageBundle>(); private readonly List<PackageBundle> _newList = new List<PackageBundle>();
private Vector2 _scrollPos1; private Vector2 _scrollPos1;
private Vector2 _scrollPos2; private Vector2 _scrollPos2;
private void OnGUI() private void OnGUI()
{ {
GUILayout.Space(10); GUILayout.Space(10);
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("选择补丁包1", GUILayout.MaxWidth(150))) if (GUILayout.Button("选择补丁包1", GUILayout.MaxWidth(150)))
{ {
string resultPath = EditorUtility.OpenFilePanel("Find", "Assets/", "bytes"); string resultPath = EditorUtility.OpenFilePanel("Find", "Assets/", "bytes");
if (string.IsNullOrEmpty(resultPath)) if (string.IsNullOrEmpty(resultPath))
return; return;
_manifestPath1 = resultPath; _manifestPath1 = resultPath;
} }
EditorGUILayout.LabelField(_manifestPath1); EditorGUILayout.LabelField(_manifestPath1);
EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal();
GUILayout.Space(10); GUILayout.Space(10);
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("选择补丁包2", GUILayout.MaxWidth(150))) if (GUILayout.Button("选择补丁包2", GUILayout.MaxWidth(150)))
{ {
string resultPath = EditorUtility.OpenFilePanel("Find", "Assets/", "bytes"); string resultPath = EditorUtility.OpenFilePanel("Find", "Assets/", "bytes");
if (string.IsNullOrEmpty(resultPath)) if (string.IsNullOrEmpty(resultPath))
return; return;
_manifestPath2 = resultPath; _manifestPath2 = resultPath;
} }
EditorGUILayout.LabelField(_manifestPath2); EditorGUILayout.LabelField(_manifestPath2);
EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal();
if (string.IsNullOrEmpty(_manifestPath1) == false && string.IsNullOrEmpty(_manifestPath2) == false) if (string.IsNullOrEmpty(_manifestPath1) == false && string.IsNullOrEmpty(_manifestPath2) == false)
{ {
if (GUILayout.Button("比对差异", GUILayout.MaxWidth(150))) if (GUILayout.Button("比对差异", GUILayout.MaxWidth(150)))
{ {
ComparePackage(_changeList, _newList); ComparePackage(_changeList, _newList);
} }
} }
EditorGUILayout.Space(); EditorGUILayout.Space();
using (new EditorGUI.DisabledScope(false)) using (new EditorGUI.DisabledScope(false))
{ {
int totalCount = _changeList.Count; int totalCount = _changeList.Count;
EditorGUILayout.Foldout(true, $"差异列表 ( {totalCount} )"); EditorGUILayout.Foldout(true, $"差异列表 ( {totalCount} )");
EditorGUI.indentLevel = 1; EditorGUI.indentLevel = 1;
_scrollPos1 = EditorGUILayout.BeginScrollView(_scrollPos1); _scrollPos1 = EditorGUILayout.BeginScrollView(_scrollPos1);
{ {
foreach (var bundle in _changeList) foreach (var bundle in _changeList)
{ {
EditorGUILayout.LabelField($"{bundle.BundleName} | {(bundle.FileSize / 1024)}K"); EditorGUILayout.LabelField($"{bundle.BundleName} | {(bundle.FileSize / 1024)}K");
} }
} }
EditorGUILayout.EndScrollView(); EditorGUILayout.EndScrollView();
EditorGUI.indentLevel = 0; EditorGUI.indentLevel = 0;
} }
EditorGUILayout.Space(); EditorGUILayout.Space();
using (new EditorGUI.DisabledScope(false)) using (new EditorGUI.DisabledScope(false))
{ {
int totalCount = _newList.Count; int totalCount = _newList.Count;
EditorGUILayout.Foldout(true, $"新增列表 ( {totalCount} )"); EditorGUILayout.Foldout(true, $"新增列表 ( {totalCount} )");
EditorGUI.indentLevel = 1; EditorGUI.indentLevel = 1;
_scrollPos2 = EditorGUILayout.BeginScrollView(_scrollPos2); _scrollPos2 = EditorGUILayout.BeginScrollView(_scrollPos2);
{ {
foreach (var bundle in _newList) foreach (var bundle in _newList)
{ {
EditorGUILayout.LabelField($"{bundle.BundleName}"); EditorGUILayout.LabelField($"{bundle.BundleName}");
} }
} }
EditorGUILayout.EndScrollView(); EditorGUILayout.EndScrollView();
EditorGUI.indentLevel = 0; EditorGUI.indentLevel = 0;
} }
} }
private void ComparePackage(List<PackageBundle> changeList, List<PackageBundle> newList) private void ComparePackage(List<PackageBundle> changeList, List<PackageBundle> newList)
{ {
changeList.Clear(); changeList.Clear();
newList.Clear(); newList.Clear();
// 加载补丁清单1 // 加载补丁清单1
byte[] bytesData1 = FileUtility.ReadAllBytes(_manifestPath1); byte[] bytesData1 = FileUtility.ReadAllBytes(_manifestPath1);
PackageManifest manifest1 = ManifestTools.DeserializeFromBinary(bytesData1); PackageManifest manifest1 = ManifestTools.DeserializeFromBinary(bytesData1);
// 加载补丁清单1 // 加载补丁清单1
byte[] bytesData2 = FileUtility.ReadAllBytes(_manifestPath2); byte[] bytesData2 = FileUtility.ReadAllBytes(_manifestPath2);
PackageManifest manifest2 = ManifestTools.DeserializeFromBinary(bytesData2); PackageManifest manifest2 = ManifestTools.DeserializeFromBinary(bytesData2);
// 拷贝文件列表 // 拷贝文件列表
foreach (var bundle2 in manifest2.BundleList) foreach (var bundle2 in manifest2.BundleList)
{ {
if (manifest1.TryGetPackageBundleByBundleName(bundle2.BundleName, out PackageBundle bundle1)) if (manifest1.TryGetPackageBundleByBundleName(bundle2.BundleName, out PackageBundle bundle1))
{ {
if (bundle2.FileHash != bundle1.FileHash) if (bundle2.FileHash != bundle1.FileHash)
{ {
changeList.Add(bundle2); changeList.Add(bundle2);
} }
} }
else else
{ {
newList.Add(bundle2); newList.Add(bundle2);
} }
} }
// 按字母重新排序 // 按字母重新排序
changeList.Sort((x, y) => string.Compare(x.BundleName, y.BundleName)); changeList.Sort((x, y) => string.Compare(x.BundleName, y.BundleName));
newList.Sort((x, y) => string.Compare(x.BundleName, y.BundleName)); newList.Sort((x, y) => string.Compare(x.BundleName, y.BundleName));
Debug.Log("资源包差异比对完成!"); Debug.Log("资源包差异比对完成!");
} }
} }
} }

View File

@ -4,88 +4,88 @@ using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class PackageImporterWindow : EditorWindow public class PackageImporterWindow : EditorWindow
{ {
static PackageImporterWindow _thisInstance; static PackageImporterWindow _thisInstance;
[MenuItem("Tools/补丁包导入工具", false, 101)] [MenuItem("Tools/补丁包导入工具", false, 101)]
static void ShowWindow() static void ShowWindow()
{ {
if (_thisInstance == null) if (_thisInstance == null)
{ {
_thisInstance = EditorWindow.GetWindow(typeof(PackageImporterWindow), false, "补丁包导入工具", true) as PackageImporterWindow; _thisInstance = EditorWindow.GetWindow(typeof(PackageImporterWindow), false, "补丁包导入工具", true) as PackageImporterWindow;
_thisInstance.minSize = new Vector2(800, 600); _thisInstance.minSize = new Vector2(800, 600);
} }
_thisInstance.Show(); _thisInstance.Show();
} }
private string _manifestPath = string.Empty; private string _manifestPath = string.Empty;
private string _packageName = "DefaultPackage"; private string _packageName = "DefaultPackage";
private void OnGUI() private void OnGUI()
{ {
GUILayout.Space(10); GUILayout.Space(10);
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("选择补丁包", GUILayout.MaxWidth(150))) if (GUILayout.Button("选择补丁包", GUILayout.MaxWidth(150)))
{ {
string resultPath = EditorUtility.OpenFilePanel("Find", "Assets/", "bytes"); string resultPath = EditorUtility.OpenFilePanel("Find", "Assets/", "bytes");
if (string.IsNullOrEmpty(resultPath)) if (string.IsNullOrEmpty(resultPath))
return; return;
_manifestPath = resultPath; _manifestPath = resultPath;
} }
EditorGUILayout.LabelField(_manifestPath); EditorGUILayout.LabelField(_manifestPath);
EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal();
if (string.IsNullOrEmpty(_manifestPath) == false) if (string.IsNullOrEmpty(_manifestPath) == false)
{ {
if (GUILayout.Button("导入补丁包(全部文件)", GUILayout.MaxWidth(150))) if (GUILayout.Button("导入补丁包(全部文件)", GUILayout.MaxWidth(150)))
{ {
string streamingAssetsRoot = AssetBundleBuilderHelper.GetStreamingAssetsRoot(); string streamingAssetsRoot = AssetBundleBuilderHelper.GetStreamingAssetsRoot();
EditorTools.ClearFolder(streamingAssetsRoot); EditorTools.ClearFolder(streamingAssetsRoot);
CopyPackageFiles(_manifestPath); CopyPackageFiles(_manifestPath);
} }
} }
} }
private void CopyPackageFiles(string manifestFilePath) private void CopyPackageFiles(string manifestFilePath)
{ {
string manifestFileName = Path.GetFileNameWithoutExtension(manifestFilePath); string manifestFileName = Path.GetFileNameWithoutExtension(manifestFilePath);
string outputDirectory = Path.GetDirectoryName(manifestFilePath); string outputDirectory = Path.GetDirectoryName(manifestFilePath);
// 加载补丁清单 // 加载补丁清单
byte[] bytesData = FileUtility.ReadAllBytes(manifestFilePath); byte[] bytesData = FileUtility.ReadAllBytes(manifestFilePath);
PackageManifest manifest = ManifestTools.DeserializeFromBinary(bytesData); PackageManifest manifest = ManifestTools.DeserializeFromBinary(bytesData);
// 拷贝核心文件 // 拷贝核心文件
{ {
string sourcePath = $"{outputDirectory}/{manifestFileName}.bytes"; string sourcePath = $"{outputDirectory}/{manifestFileName}.bytes";
string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{manifestFileName}.bytes"; string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{manifestFileName}.bytes";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
{ {
string sourcePath = $"{outputDirectory}/{manifestFileName}.hash"; string sourcePath = $"{outputDirectory}/{manifestFileName}.hash";
string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{manifestFileName}.hash"; string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{manifestFileName}.hash";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
{ {
string fileName = YooAssetSettingsData.GetPackageVersionFileName(manifest.PackageName); string fileName = YooAssetSettingsData.GetPackageVersionFileName(manifest.PackageName);
string sourcePath = $"{outputDirectory}/{fileName}"; string sourcePath = $"{outputDirectory}/{fileName}";
string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{fileName}"; string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{fileName}";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
// 拷贝文件列表 // 拷贝文件列表
int fileCount = 0; int fileCount = 0;
foreach (var packageBundle in manifest.BundleList) foreach (var packageBundle in manifest.BundleList)
{ {
fileCount++; fileCount++;
string sourcePath = $"{outputDirectory}/{packageBundle.FileName}"; string sourcePath = $"{outputDirectory}/{packageBundle.FileName}";
string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{packageBundle.FileName}"; string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsRoot()}/{_packageName}/{packageBundle.FileName}";
EditorTools.CopyFile(sourcePath, destPath, true); EditorTools.CopyFile(sourcePath, destPath, true);
} }
Debug.Log($"补丁包拷贝完成,一共拷贝了{fileCount}个资源文件"); Debug.Log($"补丁包拷贝完成,一共拷贝了{fileCount}个资源文件");
AssetDatabase.Refresh(); AssetDatabase.Refresh();
} }
} }
} }

View File

@ -9,30 +9,30 @@ using YooAsset.Editor;
public static class ShaderVariantCollectionHelper public static class ShaderVariantCollectionHelper
{ {
public static void ClearCurrentShaderVariantCollection() public static void ClearCurrentShaderVariantCollection()
{ {
EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "ClearCurrentShaderVariantCollection"); EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "ClearCurrentShaderVariantCollection");
} }
public static void SaveCurrentShaderVariantCollection(string savePath) public static void SaveCurrentShaderVariantCollection(string savePath)
{ {
EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "SaveCurrentShaderVariantCollection", savePath); EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "SaveCurrentShaderVariantCollection", savePath);
} }
public static int GetCurrentShaderVariantCollectionShaderCount() public static int GetCurrentShaderVariantCollectionShaderCount()
{ {
return (int)EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "GetCurrentShaderVariantCollectionShaderCount"); return (int)EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "GetCurrentShaderVariantCollectionShaderCount");
} }
public static int GetCurrentShaderVariantCollectionVariantCount() public static int GetCurrentShaderVariantCollectionVariantCount()
{ {
return (int)EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "GetCurrentShaderVariantCollectionVariantCount"); return (int)EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "GetCurrentShaderVariantCollectionVariantCount");
} }
/// <summary> /// <summary>
/// 获取着色器的变种总数量 /// 获取着色器的变种总数量
/// </summary> /// </summary>
public static string GetShaderVariantCount(string assetPath) public static string GetShaderVariantCount(string assetPath)
{ {
Shader shader = AssetDatabase.LoadAssetAtPath<Shader>(assetPath); Shader shader = AssetDatabase.LoadAssetAtPath<Shader>(assetPath);
var variantCount = EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "GetVariantCount", shader, true); var variantCount = EditorTools.InvokeNonPublicStaticMethod(typeof(ShaderUtil), "GetVariantCount", shader, true);
return variantCount.ToString(); return variantCount.ToString();
} }
} }

View File

@ -10,137 +10,137 @@ using UnityEditor;
[Serializable] [Serializable]
public class ShaderVariantCollectionManifest public class ShaderVariantCollectionManifest
{ {
[Serializable] [Serializable]
public class ShaderVariantElement public class ShaderVariantElement
{ {
/// <summary> /// <summary>
/// Pass type to use in this variant. /// Pass type to use in this variant.
/// </summary> /// </summary>
public PassType PassType; public PassType PassType;
/// <summary> /// <summary>
/// Array of shader keywords to use in this variant. /// Array of shader keywords to use in this variant.
/// </summary> /// </summary>
public string[] Keywords; public string[] Keywords;
} }
[Serializable] [Serializable]
public class ShaderVariantInfo public class ShaderVariantInfo
{ {
/// <summary> /// <summary>
/// 着色器资源路径. /// 着色器资源路径.
/// </summary> /// </summary>
public string AssetPath; public string AssetPath;
/// <summary> /// <summary>
/// 着色器名称 /// 着色器名称
/// </summary> /// </summary>
public string ShaderName; public string ShaderName;
/// <summary> /// <summary>
/// 着色器变种总数 /// 着色器变种总数
/// </summary> /// </summary>
public int ShaderVariantCount = 0; public int ShaderVariantCount = 0;
/// <summary> /// <summary>
/// 着色器变种列表 /// 着色器变种列表
/// </summary> /// </summary>
public List<ShaderVariantElement> ShaderVariantElements = new List<ShaderVariantElement>(1000); public List<ShaderVariantElement> ShaderVariantElements = new List<ShaderVariantElement>(1000);
} }
/// <summary> /// <summary>
/// Number of shaders in this collection /// Number of shaders in this collection
/// </summary> /// </summary>
public int ShaderTotalCount; public int ShaderTotalCount;
/// <summary> /// <summary>
/// Number of total varians in this collection /// Number of total varians in this collection
/// </summary> /// </summary>
public int VariantTotalCount; public int VariantTotalCount;
/// <summary> /// <summary>
/// Shader variants info list. /// Shader variants info list.
/// </summary> /// </summary>
public List<ShaderVariantInfo> ShaderVariantInfos = new List<ShaderVariantInfo>(1000); public List<ShaderVariantInfo> ShaderVariantInfos = new List<ShaderVariantInfo>(1000);
/// <summary> /// <summary>
/// 添加着色器变种信息 /// 添加着色器变种信息
/// </summary> /// </summary>
public void AddShaderVariant(string assetPath, string shaderName, PassType passType, string[] keywords) public void AddShaderVariant(string assetPath, string shaderName, PassType passType, string[] keywords)
{ {
var info = GetOrCreateShaderVariantInfo(assetPath, shaderName); var info = GetOrCreateShaderVariantInfo(assetPath, shaderName);
ShaderVariantElement element = new ShaderVariantElement(); ShaderVariantElement element = new ShaderVariantElement();
element.PassType = passType; element.PassType = passType;
element.Keywords = keywords; element.Keywords = keywords;
info.ShaderVariantElements.Add(element); info.ShaderVariantElements.Add(element);
info.ShaderVariantCount++; info.ShaderVariantCount++;
} }
private ShaderVariantInfo GetOrCreateShaderVariantInfo(string assetPath, string shaderName) private ShaderVariantInfo GetOrCreateShaderVariantInfo(string assetPath, string shaderName)
{ {
var selectList = ShaderVariantInfos.Where(t => t.ShaderName == shaderName && t.AssetPath == assetPath).ToList(); var selectList = ShaderVariantInfos.Where(t => t.ShaderName == shaderName && t.AssetPath == assetPath).ToList();
if (selectList.Count == 0) if (selectList.Count == 0)
{ {
ShaderVariantInfo newInfo = new ShaderVariantInfo(); ShaderVariantInfo newInfo = new ShaderVariantInfo();
newInfo.AssetPath = assetPath; newInfo.AssetPath = assetPath;
newInfo.ShaderName = shaderName; newInfo.ShaderName = shaderName;
ShaderVariantInfos.Add(newInfo); ShaderVariantInfos.Add(newInfo);
return newInfo; return newInfo;
} }
if (selectList.Count != 1) if (selectList.Count != 1)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
return selectList[0]; return selectList[0];
} }
/// <summary> /// <summary>
/// 解析SVC文件并将数据写入到清单 /// 解析SVC文件并将数据写入到清单
/// </summary> /// </summary>
public static ShaderVariantCollectionManifest Extract(ShaderVariantCollection svc) public static ShaderVariantCollectionManifest Extract(ShaderVariantCollection svc)
{ {
var manifest = new ShaderVariantCollectionManifest(); var manifest = new ShaderVariantCollectionManifest();
manifest.ShaderTotalCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionShaderCount(); manifest.ShaderTotalCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionShaderCount();
manifest.VariantTotalCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionVariantCount(); manifest.VariantTotalCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionVariantCount();
using (var so = new SerializedObject(svc)) using (var so = new SerializedObject(svc))
{ {
var shaderArray = so.FindProperty("m_Shaders.Array"); var shaderArray = so.FindProperty("m_Shaders.Array");
if (shaderArray != null && shaderArray.isArray) if (shaderArray != null && shaderArray.isArray)
{ {
for (int i = 0; i < shaderArray.arraySize; ++i) for (int i = 0; i < shaderArray.arraySize; ++i)
{ {
var shaderRef = shaderArray.FindPropertyRelative($"data[{i}].first"); var shaderRef = shaderArray.FindPropertyRelative($"data[{i}].first");
var shaderVariantsArray = shaderArray.FindPropertyRelative($"data[{i}].second.variants"); var shaderVariantsArray = shaderArray.FindPropertyRelative($"data[{i}].second.variants");
if (shaderRef != null && shaderRef.propertyType == SerializedPropertyType.ObjectReference && shaderVariantsArray != null && shaderVariantsArray.isArray) if (shaderRef != null && shaderRef.propertyType == SerializedPropertyType.ObjectReference && shaderVariantsArray != null && shaderVariantsArray.isArray)
{ {
var shader = shaderRef.objectReferenceValue as Shader; var shader = shaderRef.objectReferenceValue as Shader;
if (shader == null) if (shader == null)
{ {
throw new Exception("Invalid shader in ShaderVariantCollection file."); throw new Exception("Invalid shader in ShaderVariantCollection file.");
} }
string shaderAssetPath = AssetDatabase.GetAssetPath(shader); string shaderAssetPath = AssetDatabase.GetAssetPath(shader);
string shaderName = shader.name; string shaderName = shader.name;
// 添加变种信息 // 添加变种信息
for (int j = 0; j < shaderVariantsArray.arraySize; ++j) for (int j = 0; j < shaderVariantsArray.arraySize; ++j)
{ {
var propKeywords = shaderVariantsArray.FindPropertyRelative($"Array.data[{j}].keywords"); var propKeywords = shaderVariantsArray.FindPropertyRelative($"Array.data[{j}].keywords");
var propPassType = shaderVariantsArray.FindPropertyRelative($"Array.data[{j}].passType"); var propPassType = shaderVariantsArray.FindPropertyRelative($"Array.data[{j}].passType");
if (propKeywords != null && propPassType != null && propKeywords.propertyType == SerializedPropertyType.String) if (propKeywords != null && propPassType != null && propKeywords.propertyType == SerializedPropertyType.String)
{ {
string[] keywords = propKeywords.stringValue.Split(' '); string[] keywords = propKeywords.stringValue.Split(' ');
PassType pathType = (PassType)propPassType.intValue; PassType pathType = (PassType)propPassType.intValue;
manifest.AddShaderVariant(shaderAssetPath, shaderName, pathType, keywords); manifest.AddShaderVariant(shaderAssetPath, shaderName, pathType, keywords);
} }
} }
} }
} }
} }
} }
return manifest; return manifest;
} }
} }

View File

@ -11,246 +11,246 @@ using Debug = UnityEngine.Debug;
public static class ShaderVariantCollector public static class ShaderVariantCollector
{ {
private enum ESteps private enum ESteps
{ {
None, None,
Prepare, Prepare,
CollectAllMaterial, CollectAllMaterial,
CollectVariants, CollectVariants,
CollectSleeping, CollectSleeping,
WaitingDone, WaitingDone,
} }
private const float WaitMilliseconds = 1000f; private const float WaitMilliseconds = 1000f;
private const float SleepMilliseconds = 100f; private const float SleepMilliseconds = 100f;
private static string _savePath; private static string _savePath;
private static string _packageName; private static string _packageName;
private static int _processMaxNum; private static int _processMaxNum;
private static Action _completedCallback; private static Action _completedCallback;
private static ESteps _steps = ESteps.None; private static ESteps _steps = ESteps.None;
private static Stopwatch _elapsedTime; private static Stopwatch _elapsedTime;
private static List<string> _allMaterials; private static List<string> _allMaterials;
private static List<GameObject> _allSpheres = new List<GameObject>(1000); private static List<GameObject> _allSpheres = new List<GameObject>(1000);
/// <summary> /// <summary>
/// 开始收集 /// 开始收集
/// </summary> /// </summary>
public static void Run(string savePath, string packageName, int processMaxNum, Action completedCallback) public static void Run(string savePath, string packageName, int processMaxNum, Action completedCallback)
{ {
if (_steps != ESteps.None) if (_steps != ESteps.None)
return; return;
if (Path.HasExtension(savePath) == false) if (Path.HasExtension(savePath) == false)
savePath = $"{savePath}.shadervariants"; savePath = $"{savePath}.shadervariants";
if (Path.GetExtension(savePath) != ".shadervariants") if (Path.GetExtension(savePath) != ".shadervariants")
throw new System.Exception("Shader variant file extension is invalid."); throw new System.Exception("Shader variant file extension is invalid.");
if (string.IsNullOrEmpty(packageName)) if (string.IsNullOrEmpty(packageName))
throw new System.Exception("Package name is null or empty !"); throw new System.Exception("Package name is null or empty !");
// 注意先删除再保存否则ShaderVariantCollection内容将无法及时刷新 // 注意先删除再保存否则ShaderVariantCollection内容将无法及时刷新
AssetDatabase.DeleteAsset(savePath); AssetDatabase.DeleteAsset(savePath);
EditorTools.CreateFileDirectory(savePath); EditorTools.CreateFileDirectory(savePath);
_savePath = savePath; _savePath = savePath;
_packageName = packageName; _packageName = packageName;
_processMaxNum = processMaxNum; _processMaxNum = processMaxNum;
_completedCallback = completedCallback; _completedCallback = completedCallback;
// 聚焦到游戏窗口 // 聚焦到游戏窗口
EditorTools.FocusUnityGameWindow(); EditorTools.FocusUnityGameWindow();
// 创建临时测试场景 // 创建临时测试场景
CreateTempScene(); CreateTempScene();
_steps = ESteps.Prepare; _steps = ESteps.Prepare;
EditorApplication.update += EditorUpdate; EditorApplication.update += EditorUpdate;
} }
private static void EditorUpdate() private static void EditorUpdate()
{ {
if (_steps == ESteps.None) if (_steps == ESteps.None)
return; return;
if (_steps == ESteps.Prepare) if (_steps == ESteps.Prepare)
{ {
ShaderVariantCollectionHelper.ClearCurrentShaderVariantCollection(); ShaderVariantCollectionHelper.ClearCurrentShaderVariantCollection();
_steps = ESteps.CollectAllMaterial; _steps = ESteps.CollectAllMaterial;
return; //等待一帧 return; //等待一帧
} }
if (_steps == ESteps.CollectAllMaterial) if (_steps == ESteps.CollectAllMaterial)
{ {
_allMaterials = GetAllMaterials(); _allMaterials = GetAllMaterials();
_steps = ESteps.CollectVariants; _steps = ESteps.CollectVariants;
return; //等待一帧 return; //等待一帧
} }
if (_steps == ESteps.CollectVariants) if (_steps == ESteps.CollectVariants)
{ {
int count = Mathf.Min(_processMaxNum, _allMaterials.Count); int count = Mathf.Min(_processMaxNum, _allMaterials.Count);
List<string> range = _allMaterials.GetRange(0, count); List<string> range = _allMaterials.GetRange(0, count);
_allMaterials.RemoveRange(0, count); _allMaterials.RemoveRange(0, count);
CollectVariants(range); CollectVariants(range);
if (_allMaterials.Count > 0) if (_allMaterials.Count > 0)
{ {
_elapsedTime = Stopwatch.StartNew(); _elapsedTime = Stopwatch.StartNew();
_steps = ESteps.CollectSleeping; _steps = ESteps.CollectSleeping;
} }
else else
{ {
_elapsedTime = Stopwatch.StartNew(); _elapsedTime = Stopwatch.StartNew();
_steps = ESteps.WaitingDone; _steps = ESteps.WaitingDone;
} }
} }
if (_steps == ESteps.CollectSleeping) if (_steps == ESteps.CollectSleeping)
{ {
if (_elapsedTime.ElapsedMilliseconds > SleepMilliseconds) if (_elapsedTime.ElapsedMilliseconds > SleepMilliseconds)
{ {
DestroyAllSpheres(); DestroyAllSpheres();
_elapsedTime.Stop(); _elapsedTime.Stop();
_steps = ESteps.CollectVariants; _steps = ESteps.CollectVariants;
} }
} }
if (_steps == ESteps.WaitingDone) if (_steps == ESteps.WaitingDone)
{ {
// 注意:一定要延迟保存才会起效 // 注意:一定要延迟保存才会起效
if (_elapsedTime.ElapsedMilliseconds > WaitMilliseconds) if (_elapsedTime.ElapsedMilliseconds > WaitMilliseconds)
{ {
_elapsedTime.Stop(); _elapsedTime.Stop();
_steps = ESteps.None; _steps = ESteps.None;
// 保存结果并创建清单 // 保存结果并创建清单
ShaderVariantCollectionHelper.SaveCurrentShaderVariantCollection(_savePath); ShaderVariantCollectionHelper.SaveCurrentShaderVariantCollection(_savePath);
CreateManifest(); CreateManifest();
Debug.Log($"搜集SVC完毕"); Debug.Log($"搜集SVC完毕");
EditorApplication.update -= EditorUpdate; EditorApplication.update -= EditorUpdate;
_completedCallback?.Invoke(); _completedCallback?.Invoke();
} }
} }
} }
private static void CreateTempScene() private static void CreateTempScene()
{ {
EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
} }
private static List<string> GetAllMaterials() private static List<string> GetAllMaterials()
{ {
int progressValue = 0; int progressValue = 0;
List<string> allAssets = new List<string>(1000); List<string> allAssets = new List<string>(1000);
// 获取所有打包的资源 // 获取所有打包的资源
CollectResult collectResult = AssetBundleCollectorSettingData.Setting.GetPackageAssets(EBuildMode.DryRunBuild, _packageName); CollectResult collectResult = AssetBundleCollectorSettingData.Setting.GetPackageAssets(EBuildMode.DryRunBuild, _packageName);
foreach (var assetInfo in collectResult.CollectAssets) foreach (var assetInfo in collectResult.CollectAssets)
{ {
string[] depends = AssetDatabase.GetDependencies(assetInfo.AssetPath, true); string[] depends = AssetDatabase.GetDependencies(assetInfo.AssetPath, true);
foreach (var dependAsset in depends) foreach (var dependAsset in depends)
{ {
if (allAssets.Contains(dependAsset) == false) if (allAssets.Contains(dependAsset) == false)
allAssets.Add(dependAsset); allAssets.Add(dependAsset);
} }
EditorTools.DisplayProgressBar("获取所有打包资源", ++progressValue, collectResult.CollectAssets.Count); EditorTools.DisplayProgressBar("获取所有打包资源", ++progressValue, collectResult.CollectAssets.Count);
} }
EditorTools.ClearProgressBar(); EditorTools.ClearProgressBar();
// 搜集所有材质球 // 搜集所有材质球
progressValue = 0; progressValue = 0;
List<string> allMaterial = new List<string>(1000); List<string> allMaterial = new List<string>(1000);
foreach (var assetPath in allAssets) foreach (var assetPath in allAssets)
{ {
System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath); System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Material)) if (assetType == typeof(UnityEngine.Material))
{ {
allMaterial.Add(assetPath); allMaterial.Add(assetPath);
} }
EditorTools.DisplayProgressBar("搜集所有材质球", ++progressValue, allAssets.Count); EditorTools.DisplayProgressBar("搜集所有材质球", ++progressValue, allAssets.Count);
} }
EditorTools.ClearProgressBar(); EditorTools.ClearProgressBar();
// 返回结果 // 返回结果
return allMaterial; return allMaterial;
} }
private static void CollectVariants(List<string> materials) private static void CollectVariants(List<string> materials)
{ {
Camera camera = Camera.main; Camera camera = Camera.main;
if (camera == null) if (camera == null)
throw new System.Exception("Not found main camera."); throw new System.Exception("Not found main camera.");
// 设置主相机 // 设置主相机
float aspect = camera.aspect; float aspect = camera.aspect;
int totalMaterials = materials.Count; int totalMaterials = materials.Count;
float height = Mathf.Sqrt(totalMaterials / aspect) + 1; float height = Mathf.Sqrt(totalMaterials / aspect) + 1;
float width = Mathf.Sqrt(totalMaterials / aspect) * aspect + 1; float width = Mathf.Sqrt(totalMaterials / aspect) * aspect + 1;
float halfHeight = Mathf.CeilToInt(height / 2f); float halfHeight = Mathf.CeilToInt(height / 2f);
float halfWidth = Mathf.CeilToInt(width / 2f); float halfWidth = Mathf.CeilToInt(width / 2f);
camera.orthographic = true; camera.orthographic = true;
camera.orthographicSize = halfHeight; camera.orthographicSize = halfHeight;
camera.transform.position = new Vector3(0f, 0f, -10f); camera.transform.position = new Vector3(0f, 0f, -10f);
// 创建测试球体 // 创建测试球体
int xMax = (int)(width - 1); int xMax = (int)(width - 1);
int x = 0, y = 0; int x = 0, y = 0;
int progressValue = 0; int progressValue = 0;
for (int i = 0; i < materials.Count; i++) for (int i = 0; i < materials.Count; i++)
{ {
var material = materials[i]; var material = materials[i];
var position = new Vector3(x - halfWidth + 1f, y - halfHeight + 1f, 0f); var position = new Vector3(x - halfWidth + 1f, y - halfHeight + 1f, 0f);
var go = CreateSphere(material, position, i); var go = CreateSphere(material, position, i);
if (go != null) if (go != null)
_allSpheres.Add(go); _allSpheres.Add(go);
if (x == xMax) if (x == xMax)
{ {
x = 0; x = 0;
y++; y++;
} }
else else
{ {
x++; x++;
} }
EditorTools.DisplayProgressBar("照射所有材质球", ++progressValue, materials.Count); EditorTools.DisplayProgressBar("照射所有材质球", ++progressValue, materials.Count);
} }
EditorTools.ClearProgressBar(); EditorTools.ClearProgressBar();
} }
private static GameObject CreateSphere(string assetPath, Vector3 position, int index) private static GameObject CreateSphere(string assetPath, Vector3 position, int index)
{ {
var material = AssetDatabase.LoadAssetAtPath<Material>(assetPath); var material = AssetDatabase.LoadAssetAtPath<Material>(assetPath);
var shader = material.shader; var shader = material.shader;
if (shader == null) if (shader == null)
return null; return null;
var go = GameObject.CreatePrimitive(PrimitiveType.Sphere); var go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.GetComponent<Renderer>().sharedMaterial = material; go.GetComponent<Renderer>().sharedMaterial = material;
go.transform.position = position; go.transform.position = position;
go.name = $"Sphere_{index} | {material.name}"; go.name = $"Sphere_{index} | {material.name}";
return go; return go;
} }
private static void DestroyAllSpheres() private static void DestroyAllSpheres()
{ {
foreach (var go in _allSpheres) foreach (var go in _allSpheres)
{ {
GameObject.DestroyImmediate(go); GameObject.DestroyImmediate(go);
} }
_allSpheres.Clear(); _allSpheres.Clear();
// 尝试释放编辑器加载的资源 // 尝试释放编辑器加载的资源
EditorUtility.UnloadUnusedAssetsImmediate(true); EditorUtility.UnloadUnusedAssetsImmediate(true);
} }
private static void CreateManifest() private static void CreateManifest()
{ {
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
ShaderVariantCollection svc = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(_savePath); ShaderVariantCollection svc = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(_savePath);
if (svc != null) if (svc != null)
{ {
var wrapper = ShaderVariantCollectionManifest.Extract(svc); var wrapper = ShaderVariantCollectionManifest.Extract(svc);
string jsonData = JsonUtility.ToJson(wrapper, true); string jsonData = JsonUtility.ToJson(wrapper, true);
string savePath = _savePath.Replace(".shadervariants", ".json"); string savePath = _savePath.Replace(".shadervariants", ".json");
File.WriteAllText(savePath, jsonData); File.WriteAllText(savePath, jsonData);
} }
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
} }
} }

View File

@ -3,27 +3,27 @@ using UnityEditor;
public class ShaderVariantCollectorSetting : ScriptableObject public class ShaderVariantCollectorSetting : ScriptableObject
{ {
private const string DefaultSavePath = "Assets/MyShaderVariants.shadervariants"; private const string DefaultSavePath = "Assets/MyShaderVariants.shadervariants";
public static string GeFileSavePath(string packageName) public static string GeFileSavePath(string packageName)
{ {
string key = $"{Application.productName}_{packageName}_GeFileSavePath"; string key = $"{Application.productName}_{packageName}_GeFileSavePath";
return EditorPrefs.GetString(key, DefaultSavePath); return EditorPrefs.GetString(key, DefaultSavePath);
} }
public static void SetFileSavePath(string packageName, string savePath) public static void SetFileSavePath(string packageName, string savePath)
{ {
string key = $"{Application.productName}_{packageName}_GeFileSavePath"; string key = $"{Application.productName}_{packageName}_GeFileSavePath";
EditorPrefs.SetString(key, savePath); EditorPrefs.SetString(key, savePath);
} }
public static int GeProcessCapacity(string packageName) public static int GeProcessCapacity(string packageName)
{ {
string key = $"{Application.productName}_{packageName}_GeProcessCapacity"; string key = $"{Application.productName}_{packageName}_GeProcessCapacity";
return EditorPrefs.GetInt(key, 1000); return EditorPrefs.GetInt(key, 1000);
} }
public static void SetProcessCapacity(string packageName, int capacity) public static void SetProcessCapacity(string packageName, int capacity)
{ {
string key = $"{Application.productName}_{packageName}_GeProcessCapacity"; string key = $"{Application.productName}_{packageName}_GeProcessCapacity";
EditorPrefs.SetInt(key, capacity); EditorPrefs.SetInt(key, capacity);
} }
} }

View File

@ -10,141 +10,141 @@ using YooAsset.Editor;
public class ShaderVariantCollectorWindow : EditorWindow public class ShaderVariantCollectorWindow : EditorWindow
{ {
[MenuItem("Tools/着色器变种收集器", false, 100)] [MenuItem("Tools/着色器变种收集器", false, 100)]
public static void OpenWindow() public static void OpenWindow()
{ {
ShaderVariantCollectorWindow window = GetWindow<ShaderVariantCollectorWindow>("着色器变种收集工具", true); ShaderVariantCollectorWindow window = GetWindow<ShaderVariantCollectorWindow>("着色器变种收集工具", true);
window.minSize = new Vector2(800, 600); window.minSize = new Vector2(800, 600);
} }
private Button _collectButton; private Button _collectButton;
private TextField _collectOutputField; private TextField _collectOutputField;
private Label _currentShaderCountField; private Label _currentShaderCountField;
private Label _currentVariantCountField; private Label _currentVariantCountField;
private SliderInt _processCapacitySlider; private SliderInt _processCapacitySlider;
private PopupField<string> _packageField; private PopupField<string> _packageField;
private List<string> _packageNames; private List<string> _packageNames;
private string _currentPackageName; private string _currentPackageName;
public void CreateGUI() public void CreateGUI()
{ {
try try
{ {
VisualElement root = this.rootVisualElement; VisualElement root = this.rootVisualElement;
// 加载布局文件 // 加载布局文件
var visualAsset = UxmlLoader.LoadWindowUXML<ShaderVariantCollectorWindow>(); var visualAsset = UxmlLoader.LoadWindowUXML<ShaderVariantCollectorWindow>();
if (visualAsset == null) if (visualAsset == null)
return; return;
visualAsset.CloneTree(root); visualAsset.CloneTree(root);
// 包裹名称列表 // 包裹名称列表
_packageNames = GetBuildPackageNames(); _packageNames = GetBuildPackageNames();
_currentPackageName = _packageNames[0]; _currentPackageName = _packageNames[0];
// 文件输出目录 // 文件输出目录
_collectOutputField = root.Q<TextField>("CollectOutput"); _collectOutputField = root.Q<TextField>("CollectOutput");
_collectOutputField.SetValueWithoutNotify(ShaderVariantCollectorSetting.GeFileSavePath(_currentPackageName)); _collectOutputField.SetValueWithoutNotify(ShaderVariantCollectorSetting.GeFileSavePath(_currentPackageName));
_collectOutputField.RegisterValueChangedCallback(evt => _collectOutputField.RegisterValueChangedCallback(evt =>
{ {
ShaderVariantCollectorSetting.SetFileSavePath(_currentPackageName, _collectOutputField.value); ShaderVariantCollectorSetting.SetFileSavePath(_currentPackageName, _collectOutputField.value);
}); });
// 收集的包裹 // 收集的包裹
var packageContainer = root.Q("PackageContainer"); var packageContainer = root.Q("PackageContainer");
if (_packageNames.Count > 0) if (_packageNames.Count > 0)
{ {
int defaultIndex = GetDefaultPackageIndex(_currentPackageName); int defaultIndex = GetDefaultPackageIndex(_currentPackageName);
_packageField = new PopupField<string>(_packageNames, defaultIndex); _packageField = new PopupField<string>(_packageNames, defaultIndex);
_packageField.label = "Package"; _packageField.label = "Package";
_packageField.style.width = 350; _packageField.style.width = 350;
_packageField.RegisterValueChangedCallback(evt => _packageField.RegisterValueChangedCallback(evt =>
{ {
_currentPackageName = _packageField.value; _currentPackageName = _packageField.value;
}); });
packageContainer.Add(_packageField); packageContainer.Add(_packageField);
} }
else else
{ {
_packageField = new PopupField<string>(); _packageField = new PopupField<string>();
_packageField.label = "Package"; _packageField.label = "Package";
_packageField.style.width = 350; _packageField.style.width = 350;
packageContainer.Add(_packageField); packageContainer.Add(_packageField);
} }
// 容器值 // 容器值
_processCapacitySlider = root.Q<SliderInt>("ProcessCapacity"); _processCapacitySlider = root.Q<SliderInt>("ProcessCapacity");
_processCapacitySlider.SetValueWithoutNotify(ShaderVariantCollectorSetting.GeProcessCapacity(_currentPackageName)); _processCapacitySlider.SetValueWithoutNotify(ShaderVariantCollectorSetting.GeProcessCapacity(_currentPackageName));
#if !UNITY_2020_3_OR_NEWER #if !UNITY_2020_3_OR_NEWER
_processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})"; _processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})";
_processCapacitySlider.RegisterValueChangedCallback(evt => _processCapacitySlider.RegisterValueChangedCallback(evt =>
{ {
ShaderVariantCollectorSetting.SetProcessCapacity(_currentPackageName, _processCapacitySlider.value); ShaderVariantCollectorSetting.SetProcessCapacity(_currentPackageName, _processCapacitySlider.value);
_processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})"; _processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})";
}); });
#else #else
_processCapacitySlider.RegisterValueChangedCallback(evt => _processCapacitySlider.RegisterValueChangedCallback(evt =>
{ {
ShaderVariantCollectorSetting.SetProcessCapacity(_currentPackageName, _processCapacitySlider.value); ShaderVariantCollectorSetting.SetProcessCapacity(_currentPackageName, _processCapacitySlider.value);
}); });
#endif #endif
_currentShaderCountField = root.Q<Label>("CurrentShaderCount"); _currentShaderCountField = root.Q<Label>("CurrentShaderCount");
_currentVariantCountField = root.Q<Label>("CurrentVariantCount"); _currentVariantCountField = root.Q<Label>("CurrentVariantCount");
// 变种收集按钮 // 变种收集按钮
_collectButton = root.Q<Button>("CollectButton"); _collectButton = root.Q<Button>("CollectButton");
_collectButton.clicked += CollectButton_clicked; _collectButton.clicked += CollectButton_clicked;
} }
catch (Exception e) catch (Exception e)
{ {
Debug.LogError(e.ToString()); Debug.LogError(e.ToString());
} }
} }
private void Update() private void Update()
{ {
if (_currentShaderCountField != null) if (_currentShaderCountField != null)
{ {
int currentShaderCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionShaderCount(); int currentShaderCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionShaderCount();
_currentShaderCountField.text = $"Current Shader Count : {currentShaderCount}"; _currentShaderCountField.text = $"Current Shader Count : {currentShaderCount}";
} }
if (_currentVariantCountField != null) if (_currentVariantCountField != null)
{ {
int currentVariantCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionVariantCount(); int currentVariantCount = ShaderVariantCollectionHelper.GetCurrentShaderVariantCollectionVariantCount();
_currentVariantCountField.text = $"Current Variant Count : {currentVariantCount}"; _currentVariantCountField.text = $"Current Variant Count : {currentVariantCount}";
} }
} }
private void CollectButton_clicked() private void CollectButton_clicked()
{ {
string savePath = ShaderVariantCollectorSetting.GeFileSavePath(_currentPackageName); string savePath = ShaderVariantCollectorSetting.GeFileSavePath(_currentPackageName);
int processCapacity = _processCapacitySlider.value; int processCapacity = _processCapacitySlider.value;
ShaderVariantCollector.Run(savePath, _currentPackageName, processCapacity, null); ShaderVariantCollector.Run(savePath, _currentPackageName, processCapacity, null);
} }
// 构建包裹相关 // 构建包裹相关
private int GetDefaultPackageIndex(string packageName) private int GetDefaultPackageIndex(string packageName)
{ {
for (int index = 0; index < _packageNames.Count; index++) for (int index = 0; index < _packageNames.Count; index++)
{ {
if (_packageNames[index] == packageName) if (_packageNames[index] == packageName)
{ {
return index; return index;
} }
} }
return 0; return 0;
} }
private List<string> GetBuildPackageNames() private List<string> GetBuildPackageNames()
{ {
List<string> result = new List<string>(); List<string> result = new List<string>();
foreach (var package in AssetBundleCollectorSettingData.Setting.Packages) foreach (var package in AssetBundleCollectorSettingData.Setting.Packages)
{ {
result.Add(package.PackageName); result.Add(package.PackageName);
} }
return result; return result;
} }
} }
#endif #endif

View File

@ -5,69 +5,69 @@ using YooAsset;
[UnityEditor.CustomEditor(typeof(GameObjectAssetReference), true)] [UnityEditor.CustomEditor(typeof(GameObjectAssetReference), true)]
public class GameObjectAssetReferenceInspector : UnityEditor.Editor public class GameObjectAssetReferenceInspector : UnityEditor.Editor
{ {
private bool _init = false; private bool _init = false;
private GameObject _cacheObject; private GameObject _cacheObject;
public override void OnInspectorGUI() public override void OnInspectorGUI()
{ {
GameObjectAssetReference mono = (GameObjectAssetReference)target; GameObjectAssetReference mono = (GameObjectAssetReference)target;
if (_init == false) if (_init == false)
{ {
_init = true; _init = true;
if (string.IsNullOrEmpty(mono.AssetGUID) == false) if (string.IsNullOrEmpty(mono.AssetGUID) == false)
{ {
string assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(mono.AssetGUID); string assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(mono.AssetGUID);
if (string.IsNullOrEmpty(assetPath) == false) if (string.IsNullOrEmpty(assetPath) == false)
{ {
_cacheObject = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(assetPath); _cacheObject = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
} }
} }
} }
GameObject go = (GameObject)UnityEditor.EditorGUILayout.ObjectField(_cacheObject, typeof(GameObject), false); GameObject go = (GameObject)UnityEditor.EditorGUILayout.ObjectField(_cacheObject, typeof(GameObject), false);
if (go != _cacheObject) if (go != _cacheObject)
{ {
_cacheObject = go; _cacheObject = go;
string assetPath = UnityEditor.AssetDatabase.GetAssetPath(go); string assetPath = UnityEditor.AssetDatabase.GetAssetPath(go);
mono.AssetGUID = UnityEditor.AssetDatabase.AssetPathToGUID(assetPath); mono.AssetGUID = UnityEditor.AssetDatabase.AssetPathToGUID(assetPath);
UnityEditor.EditorUtility.SetDirty(target); UnityEditor.EditorUtility.SetDirty(target);
} }
UnityEditor.EditorGUILayout.LabelField("Asset GUID", mono.AssetGUID); UnityEditor.EditorGUILayout.LabelField("Asset GUID", mono.AssetGUID);
} }
} }
#endif #endif
public class GameObjectAssetReference : MonoBehaviour public class GameObjectAssetReference : MonoBehaviour
{ {
[HideInInspector] [HideInInspector]
public string AssetGUID = ""; public string AssetGUID = "";
private AssetHandle _handle; private AssetHandle _handle;
public void Start() public void Start()
{ {
var package = YooAssets.GetPackage("DefaultPackage"); var package = YooAssets.GetPackage("DefaultPackage");
var assetInfo = package.GetAssetInfoByGUID(AssetGUID); var assetInfo = package.GetAssetInfoByGUID(AssetGUID);
_handle = package.LoadAssetAsync(assetInfo); _handle = package.LoadAssetAsync(assetInfo);
_handle.Completed += Handle_Completed; _handle.Completed += Handle_Completed;
} }
public void OnDestroy() public void OnDestroy()
{ {
if (_handle != null) if (_handle != null)
{ {
_handle.Release(); _handle.Release();
_handle = null; _handle = null;
} }
} }
private void Handle_Completed(AssetHandle handle) private void Handle_Completed(AssetHandle handle)
{ {
if (handle.Status == EOperationStatus.Succeed) if (handle.Status == EOperationStatus.Succeed)
{ {
handle.InstantiateSync(this.transform); handle.InstantiateSync(this.transform);
} }
} }
} }

View File

@ -6,112 +6,112 @@ using YooAsset;
public class LoadAssetsByTagOperation<TObject> : GameAsyncOperation where TObject : UnityEngine.Object public class LoadAssetsByTagOperation<TObject> : GameAsyncOperation where TObject : UnityEngine.Object
{ {
private enum ESteps private enum ESteps
{ {
None, None,
LoadAssets, LoadAssets,
CheckResult, CheckResult,
Done, Done,
} }
private readonly string _tag; private readonly string _tag;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private List<AssetHandle> _handles; private List<AssetHandle> _handles;
/// <summary> /// <summary>
/// 资源对象集合 /// 资源对象集合
/// </summary> /// </summary>
public List<TObject> AssetObjects { private set; get; } public List<TObject> AssetObjects { private set; get; }
public LoadAssetsByTagOperation(string tag) public LoadAssetsByTagOperation(string tag)
{ {
_tag = tag; _tag = tag;
} }
protected override void OnStart() protected override void OnStart()
{ {
_steps = ESteps.LoadAssets; _steps = ESteps.LoadAssets;
} }
protected override void OnUpdate() protected override void OnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if (_steps == ESteps.LoadAssets) if (_steps == ESteps.LoadAssets)
{ {
AssetInfo[] assetInfos = YooAssets.GetAssetInfos(_tag); AssetInfo[] assetInfos = YooAssets.GetAssetInfos(_tag);
_handles = new List<AssetHandle>(assetInfos.Length); _handles = new List<AssetHandle>(assetInfos.Length);
foreach (var assetInfo in assetInfos) foreach (var assetInfo in assetInfos)
{ {
var handle = YooAssets.LoadAssetAsync(assetInfo); var handle = YooAssets.LoadAssetAsync(assetInfo);
_handles.Add(handle); _handles.Add(handle);
} }
_steps = ESteps.CheckResult; _steps = ESteps.CheckResult;
} }
if (_steps == ESteps.CheckResult) if (_steps == ESteps.CheckResult)
{ {
int index = 0; int index = 0;
foreach (var handle in _handles) foreach (var handle in _handles)
{ {
if (handle.IsDone == false) if (handle.IsDone == false)
{ {
Progress = (float)index / _handles.Count; Progress = (float)index / _handles.Count;
return; return;
} }
index++; index++;
} }
AssetObjects = new List<TObject>(_handles.Count); AssetObjects = new List<TObject>(_handles.Count);
foreach (var handle in _handles) foreach (var handle in _handles)
{ {
if (handle.Status == EOperationStatus.Succeed) if (handle.Status == EOperationStatus.Succeed)
{ {
var assetObject = handle.AssetObject as TObject; var assetObject = handle.AssetObject as TObject;
if (assetObject != null) if (assetObject != null)
{ {
AssetObjects.Add(assetObject); AssetObjects.Add(assetObject);
} }
else else
{ {
string error = $"资源类型转换失败:{handle.AssetObject.name}"; string error = $"资源类型转换失败:{handle.AssetObject.name}";
Debug.LogError($"{error}"); Debug.LogError($"{error}");
AssetObjects.Clear(); AssetObjects.Clear();
SetFinish(false, error); SetFinish(false, error);
return; return;
} }
} }
else else
{ {
Debug.LogError($"{handle.LastError}"); Debug.LogError($"{handle.LastError}");
AssetObjects.Clear(); AssetObjects.Clear();
SetFinish(false, handle.LastError); SetFinish(false, handle.LastError);
return; return;
} }
} }
SetFinish(true); SetFinish(true);
} }
} }
protected override void OnAbort() protected override void OnAbort()
{ {
} }
private void SetFinish(bool succeed, string error = "") private void SetFinish(bool succeed, string error = "")
{ {
Error = error; Error = error;
Status = succeed ? EOperationStatus.Succeed : EOperationStatus.Failed; Status = succeed ? EOperationStatus.Succeed : EOperationStatus.Failed;
_steps = ESteps.Done; _steps = ESteps.Done;
} }
/// <summary> /// <summary>
/// 释放资源句柄 /// 释放资源句柄
/// </summary> /// </summary>
public void ReleaseHandle() public void ReleaseHandle()
{ {
foreach (var handle in _handles) foreach (var handle in _handles)
{ {
handle.Release(); handle.Release();
} }
_handles.Clear(); _handles.Clear();
} }
} }

View File

@ -8,27 +8,27 @@ using YooAsset;
/// </summary> /// </summary>
public class FileOffsetEncryption : IEncryptionServices public class FileOffsetEncryption : IEncryptionServices
{ {
public EncryptResult Encrypt(EncryptFileInfo fileInfo) public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{ {
if (fileInfo.BundleName.Contains("_gameres_audio")) if (fileInfo.BundleName.Contains("_gameres_audio"))
{ {
int offset = 32; int offset = 32;
byte[] fileData = File.ReadAllBytes(fileInfo.FilePath); byte[] fileData = File.ReadAllBytes(fileInfo.FilePath);
var encryptedData = new byte[fileData.Length + offset]; var encryptedData = new byte[fileData.Length + offset];
Buffer.BlockCopy(fileData, 0, encryptedData, offset, fileData.Length); Buffer.BlockCopy(fileData, 0, encryptedData, offset, fileData.Length);
EncryptResult result = new EncryptResult(); EncryptResult result = new EncryptResult();
result.Encrypted = true; result.Encrypted = true;
result.EncryptedData = encryptedData; result.EncryptedData = encryptedData;
return result; return result;
} }
else else
{ {
EncryptResult result = new EncryptResult(); EncryptResult result = new EncryptResult();
result.Encrypted = false; result.Encrypted = false;
return result; return result;
} }
} }
} }
/// <summary> /// <summary>
@ -36,26 +36,26 @@ public class FileOffsetEncryption : IEncryptionServices
/// </summary> /// </summary>
public class FileStreamEncryption : IEncryptionServices public class FileStreamEncryption : IEncryptionServices
{ {
public EncryptResult Encrypt(EncryptFileInfo fileInfo) public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{ {
if (fileInfo.BundleName.Contains("_gameres_audio")) if (fileInfo.BundleName.Contains("_gameres_audio"))
{ {
var fileData = File.ReadAllBytes(fileInfo.FilePath); var fileData = File.ReadAllBytes(fileInfo.FilePath);
for (int i = 0; i < fileData.Length; i++) for (int i = 0; i < fileData.Length; i++)
{ {
fileData[i] ^= BundleStream.KEY; fileData[i] ^= BundleStream.KEY;
} }
EncryptResult result = new EncryptResult(); EncryptResult result = new EncryptResult();
result.Encrypted = true; result.Encrypted = true;
result.EncryptedData = fileData; result.EncryptedData = fileData;
return result; return result;
} }
else else
{ {
EncryptResult result = new EncryptResult(); EncryptResult result = new EncryptResult();
result.Encrypted = false; result.Encrypted = false;
return result; return result;
} }
} }
} }

View File

@ -10,7 +10,7 @@ using Random = UnityEngine.Random;
[Serializable] [Serializable]
public class RoomBoundary public class RoomBoundary
{ {
public float xMin, xMax, zMin, zMax; public float xMin, xMax, zMin, zMax;
} }
/// <summary> /// <summary>
@ -18,217 +18,217 @@ public class RoomBoundary
/// </summary> /// </summary>
public class BattleRoom public class BattleRoom
{ {
private enum ESteps private enum ESteps
{ {
None, None,
Ready, Ready,
SpawnEnemy, SpawnEnemy,
WaitSpawn, WaitSpawn,
WaitWave, WaitWave,
GameOver, GameOver,
} }
private readonly EventGroup _eventGroup = new EventGroup(); private readonly EventGroup _eventGroup = new EventGroup();
private GameObject _roomRoot; private GameObject _roomRoot;
// 关卡参数 // 关卡参数
private const int EnemyCount = 10; private const int EnemyCount = 10;
private const int EnemyScore = 10; private const int EnemyScore = 10;
private const int AsteroidScore = 1; private const int AsteroidScore = 1;
private readonly Vector3 _spawnValues = new Vector3(6, 0, 20); private readonly Vector3 _spawnValues = new Vector3(6, 0, 20);
private readonly string[] _entityLocations = new string[] private readonly string[] _entityLocations = new string[]
{ {
"asteroid01", "asteroid02", "asteroid03", "enemy_ship" "asteroid01", "asteroid02", "asteroid03", "enemy_ship"
}; };
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
private int _totalScore = 0; private int _totalScore = 0;
private int _waveSpawnCount = 0; private int _waveSpawnCount = 0;
private readonly UniTimer _startWaitTimer = UniTimer.CreateOnceTimer(1f); private readonly UniTimer _startWaitTimer = UniTimer.CreateOnceTimer(1f);
private readonly UniTimer _spawnWaitTimer = UniTimer.CreateOnceTimer(0.75f); private readonly UniTimer _spawnWaitTimer = UniTimer.CreateOnceTimer(0.75f);
private readonly UniTimer _waveWaitTimer = UniTimer.CreateOnceTimer(4f); private readonly UniTimer _waveWaitTimer = UniTimer.CreateOnceTimer(4f);
private readonly List<AssetHandle> _handles = new List<AssetHandle>(1000); private readonly List<AssetHandle> _handles = new List<AssetHandle>(1000);
/// <summary> /// <summary>
/// 初始化房间 /// 初始化房间
/// </summary> /// </summary>
public void IntRoom() public void IntRoom()
{ {
// 创建房间根对象 // 创建房间根对象
_roomRoot = new GameObject("BattleRoom"); _roomRoot = new GameObject("BattleRoom");
// 监听游戏事件 // 监听游戏事件
_eventGroup.AddListener<BattleEventDefine.PlayerDead>(OnHandleEventMessage); _eventGroup.AddListener<BattleEventDefine.PlayerDead>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.EnemyDead>(OnHandleEventMessage); _eventGroup.AddListener<BattleEventDefine.EnemyDead>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.AsteroidExplosion>(OnHandleEventMessage); _eventGroup.AddListener<BattleEventDefine.AsteroidExplosion>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.PlayerFireBullet>(OnHandleEventMessage); _eventGroup.AddListener<BattleEventDefine.PlayerFireBullet>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.EnemyFireBullet>(OnHandleEventMessage); _eventGroup.AddListener<BattleEventDefine.EnemyFireBullet>(OnHandleEventMessage);
_steps = ESteps.Ready; _steps = ESteps.Ready;
} }
/// <summary> /// <summary>
/// 销毁房间 /// 销毁房间
/// </summary> /// </summary>
public void DestroyRoom() public void DestroyRoom()
{ {
if (_eventGroup != null) if (_eventGroup != null)
_eventGroup.RemoveAllListener(); _eventGroup.RemoveAllListener();
if (_roomRoot != null) if (_roomRoot != null)
GameObject.Destroy(_roomRoot); GameObject.Destroy(_roomRoot);
foreach(var handle in _handles) foreach(var handle in _handles)
{ {
handle.Release(); handle.Release();
} }
_handles.Clear(); _handles.Clear();
} }
/// <summary> /// <summary>
/// 更新房间 /// 更新房间
/// </summary> /// </summary>
public void UpdateRoom() public void UpdateRoom()
{ {
if (_steps == ESteps.None || _steps == ESteps.GameOver) if (_steps == ESteps.None || _steps == ESteps.GameOver)
return; return;
if (_steps == ESteps.Ready) if (_steps == ESteps.Ready)
{ {
if (_startWaitTimer.Update(Time.deltaTime)) if (_startWaitTimer.Update(Time.deltaTime))
{ {
// 生成实体 // 生成实体
var handle = YooAssets.LoadAssetAsync<GameObject>("player_ship"); var handle = YooAssets.LoadAssetAsync<GameObject>("player_ship");
handle.Completed += (AssetHandle handle) => handle.Completed += (AssetHandle handle) =>
{ {
handle.InstantiateSync(_roomRoot.transform); handle.InstantiateSync(_roomRoot.transform);
}; };
_handles.Add(handle); _handles.Add(handle);
_steps = ESteps.SpawnEnemy; _steps = ESteps.SpawnEnemy;
} }
} }
if (_steps == ESteps.SpawnEnemy) if (_steps == ESteps.SpawnEnemy)
{ {
var enemyLocation = _entityLocations[Random.Range(0, 4)]; var enemyLocation = _entityLocations[Random.Range(0, 4)];
Vector3 spawnPosition = new Vector3(Random.Range(-_spawnValues.x, _spawnValues.x), _spawnValues.y, _spawnValues.z); Vector3 spawnPosition = new Vector3(Random.Range(-_spawnValues.x, _spawnValues.x), _spawnValues.y, _spawnValues.z);
Quaternion spawnRotation = Quaternion.identity; Quaternion spawnRotation = Quaternion.identity;
// 生成实体 // 生成实体
var handle = YooAssets.LoadAssetAsync<GameObject>(enemyLocation); var handle = YooAssets.LoadAssetAsync<GameObject>(enemyLocation);
handle.Completed += (AssetHandle handle) => handle.Completed += (AssetHandle handle) =>
{ {
handle.InstantiateSync(spawnPosition, spawnRotation, _roomRoot.transform); handle.InstantiateSync(spawnPosition, spawnRotation, _roomRoot.transform);
}; };
_handles.Add(handle); _handles.Add(handle);
_waveSpawnCount++; _waveSpawnCount++;
if (_waveSpawnCount >= EnemyCount) if (_waveSpawnCount >= EnemyCount)
{ {
_steps = ESteps.WaitWave; _steps = ESteps.WaitWave;
} }
else else
{ {
_steps = ESteps.WaitSpawn; _steps = ESteps.WaitSpawn;
} }
} }
if (_steps == ESteps.WaitSpawn) if (_steps == ESteps.WaitSpawn)
{ {
if (_spawnWaitTimer.Update(Time.deltaTime)) if (_spawnWaitTimer.Update(Time.deltaTime))
{ {
_spawnWaitTimer.Reset(); _spawnWaitTimer.Reset();
_steps = ESteps.SpawnEnemy; _steps = ESteps.SpawnEnemy;
} }
} }
if (_steps == ESteps.WaitWave) if (_steps == ESteps.WaitWave)
{ {
if (_waveWaitTimer.Update(Time.deltaTime)) if (_waveWaitTimer.Update(Time.deltaTime))
{ {
_waveWaitTimer.Reset(); _waveWaitTimer.Reset();
_waveSpawnCount = 0; _waveSpawnCount = 0;
_steps = ESteps.SpawnEnemy; _steps = ESteps.SpawnEnemy;
} }
} }
} }
/// <summary> /// <summary>
/// 接收事件 /// 接收事件
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
private void OnHandleEventMessage(IEventMessage message) private void OnHandleEventMessage(IEventMessage message)
{ {
if (message is BattleEventDefine.PlayerDead) if (message is BattleEventDefine.PlayerDead)
{ {
var msg = message as BattleEventDefine.PlayerDead; var msg = message as BattleEventDefine.PlayerDead;
// 创建爆炸效果 // 创建爆炸效果
var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_player"); var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_player");
handle.Completed += (AssetHandle handle) => handle.Completed += (AssetHandle handle) =>
{ {
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform); handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
}; };
_handles.Add(handle); _handles.Add(handle);
_steps = ESteps.GameOver; _steps = ESteps.GameOver;
BattleEventDefine.GameOver.SendEventMessage(); BattleEventDefine.GameOver.SendEventMessage();
} }
else if (message is BattleEventDefine.EnemyDead) else if (message is BattleEventDefine.EnemyDead)
{ {
var msg = message as BattleEventDefine.EnemyDead; var msg = message as BattleEventDefine.EnemyDead;
// 创建爆炸效果 // 创建爆炸效果
var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_enemy"); var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_enemy");
handle.Completed += (AssetHandle handle) => handle.Completed += (AssetHandle handle) =>
{ {
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform); handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
}; };
_handles.Add(handle); _handles.Add(handle);
_totalScore += EnemyScore; _totalScore += EnemyScore;
BattleEventDefine.ScoreChange.SendEventMessage(_totalScore); BattleEventDefine.ScoreChange.SendEventMessage(_totalScore);
} }
else if (message is BattleEventDefine.AsteroidExplosion) else if (message is BattleEventDefine.AsteroidExplosion)
{ {
var msg = message as BattleEventDefine.AsteroidExplosion; var msg = message as BattleEventDefine.AsteroidExplosion;
// 创建爆炸效果 // 创建爆炸效果
var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_asteroid"); var handle = YooAssets.LoadAssetAsync<GameObject>("explosion_asteroid");
handle.Completed += (AssetHandle handle) => handle.Completed += (AssetHandle handle) =>
{ {
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform); handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
}; };
_handles.Add(handle); _handles.Add(handle);
_totalScore += AsteroidScore; _totalScore += AsteroidScore;
BattleEventDefine.ScoreChange.SendEventMessage(_totalScore); BattleEventDefine.ScoreChange.SendEventMessage(_totalScore);
} }
else if (message is BattleEventDefine.PlayerFireBullet) else if (message is BattleEventDefine.PlayerFireBullet)
{ {
var msg = message as BattleEventDefine.PlayerFireBullet; var msg = message as BattleEventDefine.PlayerFireBullet;
// 创建子弹实体 // 创建子弹实体
var handle = YooAssets.LoadAssetAsync<GameObject>("player_bullet"); var handle = YooAssets.LoadAssetAsync<GameObject>("player_bullet");
handle.Completed += (AssetHandle handle) => handle.Completed += (AssetHandle handle) =>
{ {
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform); handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
}; };
_handles.Add(handle); _handles.Add(handle);
} }
else if (message is BattleEventDefine.EnemyFireBullet) else if (message is BattleEventDefine.EnemyFireBullet)
{ {
var msg = message as BattleEventDefine.EnemyFireBullet; var msg = message as BattleEventDefine.EnemyFireBullet;
// 创建子弹实体 // 创建子弹实体
var handle = YooAssets.LoadAssetAsync<GameObject>("enemy_bullet"); var handle = YooAssets.LoadAssetAsync<GameObject>("enemy_bullet");
handle.Completed += (AssetHandle handle) => handle.Completed += (AssetHandle handle) =>
{ {
handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform); handle.InstantiateSync(msg.Position, msg.Rotation, _roomRoot.transform);
}; };
_handles.Add(handle); _handles.Add(handle);
} }
} }
} }

View File

@ -4,32 +4,32 @@ using UnityEngine;
public class EntityAsteroid : MonoBehaviour public class EntityAsteroid : MonoBehaviour
{ {
public float MoveSpeed = -5f; public float MoveSpeed = -5f;
public float Tumble = 5f; public float Tumble = 5f;
private Rigidbody _rigidbody; private Rigidbody _rigidbody;
void Awake() void Awake()
{ {
_rigidbody = this.transform.GetComponent<Rigidbody>(); _rigidbody = this.transform.GetComponent<Rigidbody>();
_rigidbody.velocity = this.transform.forward * MoveSpeed; _rigidbody.velocity = this.transform.forward * MoveSpeed;
_rigidbody.angularVelocity = Random.insideUnitSphere * Tumble; _rigidbody.angularVelocity = Random.insideUnitSphere * Tumble;
} }
void OnTriggerEnter(Collider other) void OnTriggerEnter(Collider other)
{ {
var name = other.gameObject.name; var name = other.gameObject.name;
if (name.StartsWith("player")) if (name.StartsWith("player"))
{ {
BattleEventDefine.AsteroidExplosion.SendEventMessage(this.transform.position, this.transform.rotation); BattleEventDefine.AsteroidExplosion.SendEventMessage(this.transform.position, this.transform.rotation);
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
void OnTriggerExit(Collider other) void OnTriggerExit(Collider other)
{ {
var name = other.gameObject.name; var name = other.gameObject.name;
if (name.StartsWith("Boundary")) if (name.StartsWith("Boundary"))
{ {
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
} }

View File

@ -4,45 +4,45 @@ using UnityEngine;
public class EntityBullet : MonoBehaviour public class EntityBullet : MonoBehaviour
{ {
public float MoveSpeed = 20f; public float MoveSpeed = 20f;
public float DelayDestroyTime = 5f; public float DelayDestroyTime = 5f;
private Rigidbody _rigidbody; private Rigidbody _rigidbody;
void Awake() void Awake()
{ {
_rigidbody = this.transform.GetComponent<Rigidbody>(); _rigidbody = this.transform.GetComponent<Rigidbody>();
_rigidbody.velocity = this.transform.forward * MoveSpeed; _rigidbody.velocity = this.transform.forward * MoveSpeed;
} }
void OnTriggerEnter(Collider other) void OnTriggerEnter(Collider other)
{ {
var name = other.gameObject.name; var name = other.gameObject.name;
if (name.StartsWith("Boundary")) if (name.StartsWith("Boundary"))
return; return;
var goName = this.gameObject.name; var goName = this.gameObject.name;
if (goName.StartsWith("enemy_bullet")) if (goName.StartsWith("enemy_bullet"))
{ {
if (name.StartsWith("enemy") == false) if (name.StartsWith("enemy") == false)
{ {
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
if (goName.StartsWith("player_bullet")) if (goName.StartsWith("player_bullet"))
{ {
if (name.StartsWith("player") == false) if (name.StartsWith("player") == false)
{ {
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
} }
void OnTriggerExit(Collider other) void OnTriggerExit(Collider other)
{ {
var name = other.gameObject.name; var name = other.gameObject.name;
if (name.StartsWith("Boundary")) if (name.StartsWith("Boundary"))
{ {
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
} }

View File

@ -3,14 +3,14 @@ using System.Collections.Generic;
using UnityEngine; using UnityEngine;
public class EntityEffect : MonoBehaviour public class EntityEffect : MonoBehaviour
{ {
public float DelayDestroyTime = 1f; public float DelayDestroyTime = 1f;
private void Awake() private void Awake()
{ {
Invoke(nameof(DelayDestroy), DelayDestroyTime); Invoke(nameof(DelayDestroy), DelayDestroyTime);
} }
private void DelayDestroy() private void DelayDestroy()
{ {
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }

View File

@ -5,88 +5,88 @@ using Random = UnityEngine.Random;
public class EntityEnemy : MonoBehaviour public class EntityEnemy : MonoBehaviour
{ {
private const float Dodge = 5f; private const float Dodge = 5f;
private const float Smoothing = 7.5f; private const float Smoothing = 7.5f;
public RoomBoundary Boundary; public RoomBoundary Boundary;
public float MoveSpeed = 20f; public float MoveSpeed = 20f;
public float FireInterval = 2f; public float FireInterval = 2f;
public Vector2 StartWait = new Vector2(0.5f, 1f); public Vector2 StartWait = new Vector2(0.5f, 1f);
public Vector2 ManeuverTime = new Vector2(1, 2); public Vector2 ManeuverTime = new Vector2(1, 2);
public Vector2 ManeuverWait = new Vector2(1, 2); public Vector2 ManeuverWait = new Vector2(1, 2);
private Transform _shotSpawn; private Transform _shotSpawn;
private Rigidbody _rigidbody; private Rigidbody _rigidbody;
private AudioSource _audioSource; private AudioSource _audioSource;
private float _lastFireTime = 0f; private float _lastFireTime = 0f;
private float _currentSpeed; private float _currentSpeed;
private float _targetManeuver; private float _targetManeuver;
void Awake() void Awake()
{ {
_rigidbody = this.gameObject.GetComponent<Rigidbody>(); _rigidbody = this.gameObject.GetComponent<Rigidbody>();
_audioSource = this.gameObject.GetComponent<AudioSource>(); _audioSource = this.gameObject.GetComponent<AudioSource>();
_shotSpawn = this.transform.Find("shot_spawn"); _shotSpawn = this.transform.Find("shot_spawn");
_rigidbody.velocity = this.transform.forward * -5f; _rigidbody.velocity = this.transform.forward * -5f;
_lastFireTime = Time.time; _lastFireTime = Time.time;
_currentSpeed = _rigidbody.velocity.z; _currentSpeed = _rigidbody.velocity.z;
_targetManeuver = 0f; _targetManeuver = 0f;
StartCoroutine(Evade()); StartCoroutine(Evade());
} }
void Update() void Update()
{ {
if (Time.time - _lastFireTime >= FireInterval) if (Time.time - _lastFireTime >= FireInterval)
{ {
_lastFireTime = Time.time; _lastFireTime = Time.time;
_audioSource.Play(); _audioSource.Play();
BattleEventDefine.EnemyFireBullet.SendEventMessage(_shotSpawn.position, _shotSpawn.rotation); BattleEventDefine.EnemyFireBullet.SendEventMessage(_shotSpawn.position, _shotSpawn.rotation);
} }
} }
void FixedUpdate() 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.velocity = new Vector3(newManeuver, 0.0f, _currentSpeed);
_rigidbody.position = new Vector3 _rigidbody.position = new Vector3
( (
Mathf.Clamp(_rigidbody.position.x, Boundary.xMin, Boundary.xMax), Mathf.Clamp(_rigidbody.position.x, Boundary.xMin, Boundary.xMax),
0.0f, 0.0f,
Mathf.Clamp(_rigidbody.position.z, Boundary.zMin, Boundary.zMax) Mathf.Clamp(_rigidbody.position.z, Boundary.zMin, Boundary.zMax)
); );
float tilt = 10f; float tilt = 10f;
_rigidbody.rotation = Quaternion.Euler(0, 0, _rigidbody.velocity.x * -tilt); _rigidbody.rotation = Quaternion.Euler(0, 0, _rigidbody.velocity.x * -tilt);
} }
void OnTriggerEnter(Collider other) void OnTriggerEnter(Collider other)
{ {
var name = other.gameObject.name; var name = other.gameObject.name;
if (name.StartsWith("player")) if (name.StartsWith("player"))
{ {
BattleEventDefine.EnemyDead.SendEventMessage(this.transform.position, this.transform.rotation); BattleEventDefine.EnemyDead.SendEventMessage(this.transform.position, this.transform.rotation);
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
void OnTriggerExit(Collider other) void OnTriggerExit(Collider other)
{ {
var name = other.gameObject.name; var name = other.gameObject.name;
if (name.StartsWith("Boundary")) if (name.StartsWith("Boundary"))
{ {
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
IEnumerator Evade() IEnumerator Evade()
{ {
yield return new WaitForSeconds(Random.Range(StartWait.x, StartWait.y)); yield return new WaitForSeconds(Random.Range(StartWait.x, StartWait.y));
while (true) 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)); yield return new WaitForSeconds(Random.Range(ManeuverTime.x, ManeuverTime.y));
_targetManeuver = 0; _targetManeuver = 0;
yield return new WaitForSeconds(Random.Range(ManeuverWait.x, ManeuverWait.y)); yield return new WaitForSeconds(Random.Range(ManeuverWait.x, ManeuverWait.y));
} }
} }
} }

View File

@ -4,54 +4,54 @@ using UnityEngine;
public class EntityPlayer : MonoBehaviour public class EntityPlayer : MonoBehaviour
{ {
public RoomBoundary Boundary; public RoomBoundary Boundary;
public float MoveSpeed = 10f; public float MoveSpeed = 10f;
public float FireRate = 0.25f; public float FireRate = 0.25f;
private float _nextFireTime = 0f; private float _nextFireTime = 0f;
private Transform _shotSpawn; private Transform _shotSpawn;
private Rigidbody _rigidbody; private Rigidbody _rigidbody;
private AudioSource _audioSource; private AudioSource _audioSource;
void Awake() void Awake()
{ {
_rigidbody = this.gameObject.GetComponent<Rigidbody>(); _rigidbody = this.gameObject.GetComponent<Rigidbody>();
_audioSource = this.gameObject.GetComponent<AudioSource>(); _audioSource = this.gameObject.GetComponent<AudioSource>();
_shotSpawn = this.transform.Find("shot_spawn"); _shotSpawn = this.transform.Find("shot_spawn");
} }
void Update() void Update()
{ {
if (Input.GetButton("Fire1") && Time.time > _nextFireTime) if (Input.GetButton("Fire1") && Time.time > _nextFireTime)
{ {
_nextFireTime = Time.time + FireRate; _nextFireTime = Time.time + FireRate;
_audioSource.Play(); _audioSource.Play();
BattleEventDefine.PlayerFireBullet.SendEventMessage(_shotSpawn.position, _shotSpawn.rotation); BattleEventDefine.PlayerFireBullet.SendEventMessage(_shotSpawn.position, _shotSpawn.rotation);
} }
} }
void FixedUpdate() void FixedUpdate()
{ {
float moveHorizontal = Input.GetAxis("Horizontal"); float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical"); float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
_rigidbody.velocity = movement * MoveSpeed; _rigidbody.velocity = movement * MoveSpeed;
_rigidbody.position = new Vector3 _rigidbody.position = new Vector3
( (
Mathf.Clamp(GetComponent<Rigidbody>().position.x, Boundary.xMin, Boundary.xMax), Mathf.Clamp(GetComponent<Rigidbody>().position.x, Boundary.xMin, Boundary.xMax),
0.0f, 0.0f,
Mathf.Clamp(GetComponent<Rigidbody>().position.z, Boundary.zMin, Boundary.zMax) Mathf.Clamp(GetComponent<Rigidbody>().position.z, Boundary.zMin, Boundary.zMax)
); );
float tilt = 5f; float tilt = 5f;
_rigidbody.rotation = Quaternion.Euler(0.0f, 0.0f, _rigidbody.velocity.x * -tilt); _rigidbody.rotation = Quaternion.Euler(0.0f, 0.0f, _rigidbody.velocity.x * -tilt);
} }
void OnTriggerEnter(Collider other) void OnTriggerEnter(Collider other)
{ {
var name = other.gameObject.name; var name = other.gameObject.name;
if (name.StartsWith("enemy") || name.StartsWith("asteroid")) if (name.StartsWith("enemy") || name.StartsWith("asteroid"))
{ {
BattleEventDefine.PlayerDead.SendEventMessage(this.transform.position, this.transform.rotation); BattleEventDefine.PlayerDead.SendEventMessage(this.transform.position, this.transform.rotation);
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }
} }

View File

@ -4,12 +4,12 @@ using YooAsset;
public class ApplicationQuit : MonoBehaviour public class ApplicationQuit : MonoBehaviour
{ {
private void Awake() private void Awake()
{ {
DontDestroyOnLoad(this.gameObject); DontDestroyOnLoad(this.gameObject);
} }
private void OnApplicationQuit() private void OnApplicationQuit()
{ {
YooAssets.Destroy(); YooAssets.Destroy();
} }
} }

View File

@ -3,19 +3,19 @@ using UnityEngine;
public class BackgroundScroller : MonoBehaviour public class BackgroundScroller : MonoBehaviour
{ {
public float ScrollSpeed; public float ScrollSpeed;
public float TileSizeZ; public float TileSizeZ;
private Vector3 _startPosition; private Vector3 _startPosition;
void Start () void Start ()
{ {
_startPosition = transform.position; _startPosition = transform.position;
} }
void Update () void Update ()
{ {
float newPosition = Mathf.Repeat(Time.time * ScrollSpeed, TileSizeZ); float newPosition = Mathf.Repeat(Time.time * ScrollSpeed, TileSizeZ);
this.transform.position = _startPosition + Vector3.forward * newPosition; this.transform.position = _startPosition + Vector3.forward * newPosition;
} }
} }

View File

@ -7,43 +7,43 @@ using YooAsset;
public class Boot : MonoBehaviour public class Boot : MonoBehaviour
{ {
/// <summary> /// <summary>
/// 资源系统运行模式 /// 资源系统运行模式
/// </summary> /// </summary>
public EPlayMode PlayMode = EPlayMode.EditorSimulateMode; public EPlayMode PlayMode = EPlayMode.EditorSimulateMode;
void Awake() void Awake()
{ {
Debug.Log($"资源系统运行模式:{PlayMode}"); Debug.Log($"资源系统运行模式:{PlayMode}");
Application.targetFrameRate = 60; Application.targetFrameRate = 60;
Application.runInBackground = true; Application.runInBackground = true;
DontDestroyOnLoad(this.gameObject); DontDestroyOnLoad(this.gameObject);
} }
IEnumerator Start() IEnumerator Start()
{ {
// 游戏管理器 // 游戏管理器
GameManager.Instance.Behaviour = this; GameManager.Instance.Behaviour = this;
// 初始化事件系统 // 初始化事件系统
UniEvent.Initalize(); UniEvent.Initalize();
// 初始化资源系统 // 初始化资源系统
YooAssets.Initialize(); YooAssets.Initialize();
// 加载更新页面 // 加载更新页面
var go = Resources.Load<GameObject>("PatchWindow"); var go = Resources.Load<GameObject>("PatchWindow");
GameObject.Instantiate(go); GameObject.Instantiate(go);
// 开始补丁更新流程 // 开始补丁更新流程
PatchOperation operation = new PatchOperation("DefaultPackage", EDefaultBuildPipeline.BuiltinBuildPipeline.ToString(), PlayMode); PatchOperation operation = new PatchOperation("DefaultPackage", EDefaultBuildPipeline.BuiltinBuildPipeline.ToString(), PlayMode);
YooAssets.StartOperation(operation); YooAssets.StartOperation(operation);
yield return operation; yield return operation;
// 设置默认的资源包 // 设置默认的资源包
var gamePackage = YooAssets.GetPackage("DefaultPackage"); var gamePackage = YooAssets.GetPackage("DefaultPackage");
YooAssets.SetDefaultPackage(gamePackage); YooAssets.SetDefaultPackage(gamePackage);
// 切换到主页面场景 // 切换到主页面场景
SceneEventDefine.ChangeToHomeScene.SendEventMessage(); SceneEventDefine.ChangeToHomeScene.SendEventMessage();
} }
} }

View File

@ -5,115 +5,115 @@ using UniFramework.Event;
public class BattleEventDefine public class BattleEventDefine
{ {
/// <summary> /// <summary>
/// 分数改变 /// 分数改变
/// </summary> /// </summary>
public class ScoreChange : IEventMessage public class ScoreChange : IEventMessage
{ {
public int CurrentScores; public int CurrentScores;
public static void SendEventMessage(int currentScores) public static void SendEventMessage(int currentScores)
{ {
var msg = new ScoreChange(); var msg = new ScoreChange();
msg.CurrentScores = currentScores; msg.CurrentScores = currentScores;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 游戏结束 /// 游戏结束
/// </summary> /// </summary>
public class GameOver : IEventMessage public class GameOver : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new GameOver(); var msg = new GameOver();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 敌人死亡 /// 敌人死亡
/// </summary> /// </summary>
public class EnemyDead : IEventMessage public class EnemyDead : IEventMessage
{ {
public Vector3 Position; public Vector3 Position;
public Quaternion Rotation; public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation) public static void SendEventMessage(Vector3 position, Quaternion rotation)
{ {
var msg = new EnemyDead(); var msg = new EnemyDead();
msg.Position = position; msg.Position = position;
msg.Rotation = rotation; msg.Rotation = rotation;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 玩家死亡 /// 玩家死亡
/// </summary> /// </summary>
public class PlayerDead : IEventMessage public class PlayerDead : IEventMessage
{ {
public Vector3 Position; public Vector3 Position;
public Quaternion Rotation; public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation) public static void SendEventMessage(Vector3 position, Quaternion rotation)
{ {
var msg = new PlayerDead(); var msg = new PlayerDead();
msg.Position = position; msg.Position = position;
msg.Rotation = rotation; msg.Rotation = rotation;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 小行星爆炸 /// 小行星爆炸
/// </summary> /// </summary>
public class AsteroidExplosion : IEventMessage public class AsteroidExplosion : IEventMessage
{ {
public Vector3 Position; public Vector3 Position;
public Quaternion Rotation; public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation) public static void SendEventMessage(Vector3 position, Quaternion rotation)
{ {
var msg = new AsteroidExplosion(); var msg = new AsteroidExplosion();
msg.Position = position; msg.Position = position;
msg.Rotation = rotation; msg.Rotation = rotation;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 敌人发射子弹 /// 敌人发射子弹
/// </summary> /// </summary>
public class EnemyFireBullet : IEventMessage public class EnemyFireBullet : IEventMessage
{ {
public Vector3 Position; public Vector3 Position;
public Quaternion Rotation; public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation) public static void SendEventMessage(Vector3 position, Quaternion rotation)
{ {
var msg = new EnemyFireBullet(); var msg = new EnemyFireBullet();
msg.Position = position; msg.Position = position;
msg.Rotation = rotation; msg.Rotation = rotation;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 玩家发射子弹 /// 玩家发射子弹
/// </summary> /// </summary>
public class PlayerFireBullet : IEventMessage public class PlayerFireBullet : IEventMessage
{ {
public Vector3 Position; public Vector3 Position;
public Quaternion Rotation; public Quaternion Rotation;
public static void SendEventMessage(Vector3 position, Quaternion rotation) public static void SendEventMessage(Vector3 position, Quaternion rotation)
{ {
var msg = new PlayerFireBullet(); var msg = new PlayerFireBullet();
msg.Position = position; msg.Position = position;
msg.Rotation = rotation; msg.Rotation = rotation;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
} }

View File

@ -2,109 +2,109 @@
public class PatchEventDefine public class PatchEventDefine
{ {
/// <summary> /// <summary>
/// 补丁包初始化失败 /// 补丁包初始化失败
/// </summary> /// </summary>
public class InitializeFailed : IEventMessage public class InitializeFailed : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new InitializeFailed(); var msg = new InitializeFailed();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 补丁流程步骤改变 /// 补丁流程步骤改变
/// </summary> /// </summary>
public class PatchStatesChange : IEventMessage public class PatchStatesChange : IEventMessage
{ {
public string Tips; public string Tips;
public static void SendEventMessage(string tips) public static void SendEventMessage(string tips)
{ {
var msg = new PatchStatesChange(); var msg = new PatchStatesChange();
msg.Tips = tips; msg.Tips = tips;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 发现更新文件 /// 发现更新文件
/// </summary> /// </summary>
public class FoundUpdateFiles : IEventMessage public class FoundUpdateFiles : IEventMessage
{ {
public int TotalCount; public int TotalCount;
public long TotalSizeBytes; public long TotalSizeBytes;
public static void SendEventMessage(int totalCount, long totalSizeBytes) public static void SendEventMessage(int totalCount, long totalSizeBytes)
{ {
var msg = new FoundUpdateFiles(); var msg = new FoundUpdateFiles();
msg.TotalCount = totalCount; msg.TotalCount = totalCount;
msg.TotalSizeBytes = totalSizeBytes; msg.TotalSizeBytes = totalSizeBytes;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 下载进度更新 /// 下载进度更新
/// </summary> /// </summary>
public class DownloadProgressUpdate : IEventMessage public class DownloadProgressUpdate : IEventMessage
{ {
public int TotalDownloadCount; public int TotalDownloadCount;
public int CurrentDownloadCount; public int CurrentDownloadCount;
public long TotalDownloadSizeBytes; public long TotalDownloadSizeBytes;
public long CurrentDownloadSizeBytes; public long CurrentDownloadSizeBytes;
public static void SendEventMessage(int totalDownloadCount, int currentDownloadCount, long totalDownloadSizeBytes, long currentDownloadSizeBytes) public static void SendEventMessage(int totalDownloadCount, int currentDownloadCount, long totalDownloadSizeBytes, long currentDownloadSizeBytes)
{ {
var msg = new DownloadProgressUpdate(); var msg = new DownloadProgressUpdate();
msg.TotalDownloadCount = totalDownloadCount; msg.TotalDownloadCount = totalDownloadCount;
msg.CurrentDownloadCount = currentDownloadCount; msg.CurrentDownloadCount = currentDownloadCount;
msg.TotalDownloadSizeBytes = totalDownloadSizeBytes; msg.TotalDownloadSizeBytes = totalDownloadSizeBytes;
msg.CurrentDownloadSizeBytes = currentDownloadSizeBytes; msg.CurrentDownloadSizeBytes = currentDownloadSizeBytes;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 资源版本号更新失败 /// 资源版本号更新失败
/// </summary> /// </summary>
public class PackageVersionUpdateFailed : IEventMessage public class PackageVersionUpdateFailed : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new PackageVersionUpdateFailed(); var msg = new PackageVersionUpdateFailed();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 补丁清单更新失败 /// 补丁清单更新失败
/// </summary> /// </summary>
public class PatchManifestUpdateFailed : IEventMessage public class PatchManifestUpdateFailed : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new PatchManifestUpdateFailed(); var msg = new PatchManifestUpdateFailed();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 网络文件下载失败 /// 网络文件下载失败
/// </summary> /// </summary>
public class WebFileDownloadFailed : IEventMessage public class WebFileDownloadFailed : IEventMessage
{ {
public string FileName; public string FileName;
public string Error; public string Error;
public static void SendEventMessage(string fileName, string error) public static void SendEventMessage(string fileName, string error)
{ {
var msg = new WebFileDownloadFailed(); var msg = new WebFileDownloadFailed();
msg.FileName = fileName; msg.FileName = fileName;
msg.Error = error; msg.Error = error;
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
} }

View File

@ -2,21 +2,21 @@
public class SceneEventDefine public class SceneEventDefine
{ {
public class ChangeToHomeScene : IEventMessage public class ChangeToHomeScene : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new ChangeToHomeScene(); var msg = new ChangeToHomeScene();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
public class ChangeToBattleScene : IEventMessage public class ChangeToBattleScene : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new ChangeToBattleScene(); var msg = new ChangeToBattleScene();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
} }

View File

@ -2,63 +2,63 @@
public class UserEventDefine public class UserEventDefine
{ {
/// <summary> /// <summary>
/// 用户尝试再次初始化资源包 /// 用户尝试再次初始化资源包
/// </summary> /// </summary>
public class UserTryInitialize : IEventMessage public class UserTryInitialize : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new UserTryInitialize(); var msg = new UserTryInitialize();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 用户开始下载网络文件 /// 用户开始下载网络文件
/// </summary> /// </summary>
public class UserBeginDownloadWebFiles : IEventMessage public class UserBeginDownloadWebFiles : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new UserBeginDownloadWebFiles(); var msg = new UserBeginDownloadWebFiles();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 用户尝试再次更新静态版本 /// 用户尝试再次更新静态版本
/// </summary> /// </summary>
public class UserTryUpdatePackageVersion : IEventMessage public class UserTryUpdatePackageVersion : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new UserTryUpdatePackageVersion(); var msg = new UserTryUpdatePackageVersion();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 用户尝试再次更新补丁清单 /// 用户尝试再次更新补丁清单
/// </summary> /// </summary>
public class UserTryUpdatePatchManifest : IEventMessage public class UserTryUpdatePatchManifest : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new UserTryUpdatePatchManifest(); var msg = new UserTryUpdatePatchManifest();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
/// <summary> /// <summary>
/// 用户尝试再次下载网络文件 /// 用户尝试再次下载网络文件
/// </summary> /// </summary>
public class UserTryDownloadWebFiles : IEventMessage public class UserTryDownloadWebFiles : IEventMessage
{ {
public static void SendEventMessage() public static void SendEventMessage()
{ {
var msg = new UserTryDownloadWebFiles(); var msg = new UserTryDownloadWebFiles();
UniEvent.SendMessage(msg); UniEvent.SendMessage(msg);
} }
} }
} }

View File

@ -6,52 +6,52 @@ using YooAsset;
public class GameManager public class GameManager
{ {
private static GameManager _instance; private static GameManager _instance;
public static GameManager Instance public static GameManager Instance
{ {
get get
{ {
if (_instance == null) if (_instance == null)
_instance = new GameManager(); _instance = new GameManager();
return _instance; return _instance;
} }
} }
private readonly EventGroup _eventGroup = new EventGroup(); private readonly EventGroup _eventGroup = new EventGroup();
/// <summary> /// <summary>
/// 协程启动器 /// 协程启动器
/// </summary> /// </summary>
public MonoBehaviour Behaviour; public MonoBehaviour Behaviour;
private GameManager() private GameManager()
{ {
// 注册监听事件 // 注册监听事件
_eventGroup.AddListener<SceneEventDefine.ChangeToHomeScene>(OnHandleEventMessage); _eventGroup.AddListener<SceneEventDefine.ChangeToHomeScene>(OnHandleEventMessage);
_eventGroup.AddListener<SceneEventDefine.ChangeToBattleScene>(OnHandleEventMessage); _eventGroup.AddListener<SceneEventDefine.ChangeToBattleScene>(OnHandleEventMessage);
} }
/// <summary> /// <summary>
/// 开启一个协程 /// 开启一个协程
/// </summary> /// </summary>
public void StartCoroutine(IEnumerator enumerator) public void StartCoroutine(IEnumerator enumerator)
{ {
Behaviour.StartCoroutine(enumerator); Behaviour.StartCoroutine(enumerator);
} }
/// <summary> /// <summary>
/// 接收事件 /// 接收事件
/// </summary> /// </summary>
private void OnHandleEventMessage(IEventMessage message) private void OnHandleEventMessage(IEventMessage message)
{ {
if (message is SceneEventDefine.ChangeToHomeScene) if (message is SceneEventDefine.ChangeToHomeScene)
{ {
YooAssets.LoadSceneAsync("scene_home"); YooAssets.LoadSceneAsync("scene_home");
} }
else if (message is SceneEventDefine.ChangeToBattleScene) else if (message is SceneEventDefine.ChangeToBattleScene)
{ {
YooAssets.LoadSceneAsync("scene_battle"); YooAssets.LoadSceneAsync("scene_battle");
} }
} }
} }

View File

@ -8,63 +8,63 @@ using YooAsset;
internal class SceneBattle : MonoBehaviour internal class SceneBattle : MonoBehaviour
{ {
public GameObject CanvasDesktop; public GameObject CanvasDesktop;
private AssetHandle _windowHandle; private AssetHandle _windowHandle;
private AssetHandle _musicHandle; private AssetHandle _musicHandle;
private BattleRoom _battleRoom; private BattleRoom _battleRoom;
private IEnumerator Start() private IEnumerator Start()
{ {
// 加载战斗页面 // 加载战斗页面
_windowHandle = YooAssets.LoadAssetAsync<GameObject>("UIBattle"); _windowHandle = YooAssets.LoadAssetAsync<GameObject>("UIBattle");
yield return _windowHandle; yield return _windowHandle;
_windowHandle.InstantiateSync(CanvasDesktop.transform); _windowHandle.InstantiateSync(CanvasDesktop.transform);
// 加载背景音乐 // 加载背景音乐
var package = YooAssets.GetPackage("DefaultPackage"); var package = YooAssets.GetPackage("DefaultPackage");
_musicHandle = package.LoadAssetAsync<AudioClip>("music_background"); _musicHandle = package.LoadAssetAsync<AudioClip>("music_background");
yield return _musicHandle; yield return _musicHandle;
// 播放背景音乐 // 播放背景音乐
var audioSource = this.gameObject.AddComponent<AudioSource>(); var audioSource = this.gameObject.AddComponent<AudioSource>();
audioSource.loop = true; audioSource.loop = true;
audioSource.clip = _musicHandle.AssetObject as AudioClip; audioSource.clip = _musicHandle.AssetObject as AudioClip;
audioSource.Play(); audioSource.Play();
_battleRoom = new BattleRoom(); _battleRoom = new BattleRoom();
_battleRoom.IntRoom(); _battleRoom.IntRoom();
} }
private void OnDestroy() private void OnDestroy()
{ {
if (_windowHandle != null) if (_windowHandle != null)
{ {
_windowHandle.Release(); _windowHandle.Release();
_windowHandle = null; _windowHandle = null;
} }
if (_musicHandle != null) if (_musicHandle != null)
{ {
_musicHandle.Release(); _musicHandle.Release();
_musicHandle = null; _musicHandle = null;
} }
if (_battleRoom != null) if (_battleRoom != null)
{ {
_battleRoom.DestroyRoom(); _battleRoom.DestroyRoom();
_battleRoom = null; _battleRoom = null;
} }
// 切换场景的时候释放资源 // 切换场景的时候释放资源
if (YooAssets.Initialized) if (YooAssets.Initialized)
{ {
var package = YooAssets.GetPackage("DefaultPackage"); var package = YooAssets.GetPackage("DefaultPackage");
package.UnloadUnusedAssets(); package.UnloadUnusedAssets();
} }
} }
private void Update() private void Update()
{ {
if (_battleRoom != null) if (_battleRoom != null)
_battleRoom.UpdateRoom(); _battleRoom.UpdateRoom();
} }
} }

View File

@ -5,30 +5,30 @@ using YooAsset;
public class SceneHome : MonoBehaviour public class SceneHome : MonoBehaviour
{ {
public GameObject CanvasDesktop; public GameObject CanvasDesktop;
private AssetHandle _windowHandle; private AssetHandle _windowHandle;
private IEnumerator Start() private IEnumerator Start()
{ {
// 加载登录页面 // 加载登录页面
_windowHandle = YooAssets.LoadAssetAsync<GameObject>("UIHome"); _windowHandle = YooAssets.LoadAssetAsync<GameObject>("UIHome");
yield return _windowHandle; yield return _windowHandle;
_windowHandle.InstantiateSync(CanvasDesktop.transform); _windowHandle.InstantiateSync(CanvasDesktop.transform);
} }
private void OnDestroy() private void OnDestroy()
{ {
if (_windowHandle != null) if (_windowHandle != null)
{ {
_windowHandle.Release(); _windowHandle.Release();
_windowHandle = null; _windowHandle = null;
} }
// 切换场景的时候释放资源 // 切换场景的时候释放资源
if (YooAssets.Initialized) if (YooAssets.Initialized)
{ {
var package = YooAssets.GetPackage("DefaultPackage"); var package = YooAssets.GetPackage("DefaultPackage");
package.UnloadUnusedAssets(); package.UnloadUnusedAssets();
} }
} }
} }

View File

@ -9,29 +9,29 @@ using YooAsset;
/// </summary> /// </summary>
internal class FsmClearPackageCache : IStateNode internal class FsmClearPackageCache : IStateNode
{ {
private StateMachine _machine; private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
_machine = machine; _machine = machine;
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
PatchEventDefine.PatchStatesChange.SendEventMessage("清理未使用的缓存文件!"); PatchEventDefine.PatchStatesChange.SendEventMessage("清理未使用的缓存文件!");
var packageName = (string)_machine.GetBlackboardValue("PackageName"); var packageName = (string)_machine.GetBlackboardValue("PackageName");
var package = YooAssets.GetPackage(packageName); var package = YooAssets.GetPackage(packageName);
var operation = package.ClearUnusedCacheFilesAsync(); var operation = package.ClearUnusedCacheFilesAsync();
operation.Completed += Operation_Completed; operation.Completed += Operation_Completed;
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
private void Operation_Completed(YooAsset.AsyncOperationBase obj) private void Operation_Completed(YooAsset.AsyncOperationBase obj)
{ {
_machine.ChangeState<FsmUpdaterDone>(); _machine.ChangeState<FsmUpdaterDone>();
} }
} }

View File

@ -9,47 +9,47 @@ using YooAsset;
/// </summary> /// </summary>
public class FsmCreatePackageDownloader : IStateNode public class FsmCreatePackageDownloader : IStateNode
{ {
private StateMachine _machine; private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
_machine = machine; _machine = machine;
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
PatchEventDefine.PatchStatesChange.SendEventMessage("创建补丁下载器!"); PatchEventDefine.PatchStatesChange.SendEventMessage("创建补丁下载器!");
GameManager.Instance.StartCoroutine(CreateDownloader()); GameManager.Instance.StartCoroutine(CreateDownloader());
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
IEnumerator CreateDownloader() IEnumerator CreateDownloader()
{ {
yield return new WaitForSecondsRealtime(0.5f); yield return new WaitForSecondsRealtime(0.5f);
var packageName = (string)_machine.GetBlackboardValue("PackageName"); var packageName = (string)_machine.GetBlackboardValue("PackageName");
var package = YooAssets.GetPackage(packageName); var package = YooAssets.GetPackage(packageName);
int downloadingMaxNum = 10; int downloadingMaxNum = 10;
int failedTryAgain = 3; int failedTryAgain = 3;
var downloader = package.CreateResourceDownloader(downloadingMaxNum, failedTryAgain); var downloader = package.CreateResourceDownloader(downloadingMaxNum, failedTryAgain);
_machine.SetBlackboardValue("Downloader", downloader); _machine.SetBlackboardValue("Downloader", downloader);
if (downloader.TotalDownloadCount == 0) if (downloader.TotalDownloadCount == 0)
{ {
Debug.Log("Not found any download files !"); Debug.Log("Not found any download files !");
_machine.ChangeState<FsmUpdaterDone>(); _machine.ChangeState<FsmUpdaterDone>();
} }
else else
{ {
// 发现新更新文件后,挂起流程系统 // 发现新更新文件后,挂起流程系统
// 注意:开发者需要在下载前检测磁盘空间不足 // 注意:开发者需要在下载前检测磁盘空间不足
int totalDownloadCount = downloader.TotalDownloadCount; int totalDownloadCount = downloader.TotalDownloadCount;
long totalDownloadBytes = downloader.TotalDownloadBytes; long totalDownloadBytes = downloader.TotalDownloadBytes;
PatchEventDefine.FoundUpdateFiles.SendEventMessage(totalDownloadCount, totalDownloadBytes); PatchEventDefine.FoundUpdateFiles.SendEventMessage(totalDownloadCount, totalDownloadBytes);
} }
} }
} }

View File

@ -8,36 +8,36 @@ using YooAsset;
/// </summary> /// </summary>
public class FsmDownloadPackageFiles : IStateNode public class FsmDownloadPackageFiles : IStateNode
{ {
private StateMachine _machine; private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
_machine = machine; _machine = machine;
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
PatchEventDefine.PatchStatesChange.SendEventMessage("开始下载补丁文件!"); PatchEventDefine.PatchStatesChange.SendEventMessage("开始下载补丁文件!");
GameManager.Instance.StartCoroutine(BeginDownload()); GameManager.Instance.StartCoroutine(BeginDownload());
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
private IEnumerator BeginDownload() private IEnumerator BeginDownload()
{ {
var downloader = (ResourceDownloaderOperation)_machine.GetBlackboardValue("Downloader"); var downloader = (ResourceDownloaderOperation)_machine.GetBlackboardValue("Downloader");
downloader.OnDownloadErrorCallback = PatchEventDefine.WebFileDownloadFailed.SendEventMessage; downloader.OnDownloadErrorCallback = PatchEventDefine.WebFileDownloadFailed.SendEventMessage;
downloader.OnDownloadProgressCallback = PatchEventDefine.DownloadProgressUpdate.SendEventMessage; downloader.OnDownloadProgressCallback = PatchEventDefine.DownloadProgressUpdate.SendEventMessage;
downloader.BeginDownload(); downloader.BeginDownload();
yield return downloader; yield return downloader;
// 检测下载结果 // 检测下载结果
if (downloader.Status != EOperationStatus.Succeed) if (downloader.Status != EOperationStatus.Succeed)
yield break; yield break;
_machine.ChangeState<FsmDownloadPackageOver>(); _machine.ChangeState<FsmDownloadPackageOver>();
} }
} }

View File

@ -8,20 +8,20 @@ using UniFramework.Machine;
/// </summary> /// </summary>
internal class FsmDownloadPackageOver : IStateNode internal class FsmDownloadPackageOver : IStateNode
{ {
private StateMachine _machine; private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
_machine = machine; _machine = machine;
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
_machine.ChangeState<FsmClearPackageCache>(); _machine.ChangeState<FsmClearPackageCache>();
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
} }

View File

@ -11,208 +11,208 @@ using YooAsset;
/// </summary> /// </summary>
internal class FsmInitializePackage : IStateNode internal class FsmInitializePackage : IStateNode
{ {
private StateMachine _machine; private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
_machine = machine; _machine = machine;
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
PatchEventDefine.PatchStatesChange.SendEventMessage("初始化资源包!"); PatchEventDefine.PatchStatesChange.SendEventMessage("初始化资源包!");
GameManager.Instance.StartCoroutine(InitPackage()); GameManager.Instance.StartCoroutine(InitPackage());
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
private IEnumerator InitPackage() private IEnumerator InitPackage()
{ {
var playMode = (EPlayMode)_machine.GetBlackboardValue("PlayMode"); var playMode = (EPlayMode)_machine.GetBlackboardValue("PlayMode");
var packageName = (string)_machine.GetBlackboardValue("PackageName"); var packageName = (string)_machine.GetBlackboardValue("PackageName");
var buildPipeline = (string)_machine.GetBlackboardValue("BuildPipeline"); var buildPipeline = (string)_machine.GetBlackboardValue("BuildPipeline");
// 创建资源包裹类 // 创建资源包裹类
var package = YooAssets.TryGetPackage(packageName); var package = YooAssets.TryGetPackage(packageName);
if (package == null) if (package == null)
package = YooAssets.CreatePackage(packageName); package = YooAssets.CreatePackage(packageName);
// 编辑器下的模拟模式 // 编辑器下的模拟模式
InitializationOperation initializationOperation = null; InitializationOperation initializationOperation = null;
if (playMode == EPlayMode.EditorSimulateMode) if (playMode == EPlayMode.EditorSimulateMode)
{ {
var createParameters = new EditorSimulateModeParameters(); var createParameters = new EditorSimulateModeParameters();
createParameters.SimulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild(buildPipeline, packageName); createParameters.SimulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild(buildPipeline, packageName);
initializationOperation = package.InitializeAsync(createParameters); initializationOperation = package.InitializeAsync(createParameters);
} }
// 单机运行模式 // 单机运行模式
if (playMode == EPlayMode.OfflinePlayMode) if (playMode == EPlayMode.OfflinePlayMode)
{ {
var createParameters = new OfflinePlayModeParameters(); var createParameters = new OfflinePlayModeParameters();
createParameters.DecryptionServices = new FileStreamDecryption(); createParameters.DecryptionServices = new FileStreamDecryption();
initializationOperation = package.InitializeAsync(createParameters); initializationOperation = package.InitializeAsync(createParameters);
} }
// 联机运行模式 // 联机运行模式
if (playMode == EPlayMode.HostPlayMode) if (playMode == EPlayMode.HostPlayMode)
{ {
string defaultHostServer = GetHostServerURL(); string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL(); string fallbackHostServer = GetHostServerURL();
var createParameters = new HostPlayModeParameters(); var createParameters = new HostPlayModeParameters();
createParameters.DecryptionServices = new FileStreamDecryption(); createParameters.DecryptionServices = new FileStreamDecryption();
createParameters.BuildinQueryServices = new GameQueryServices(); createParameters.BuildinQueryServices = new GameQueryServices();
createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer); createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
initializationOperation = package.InitializeAsync(createParameters); initializationOperation = package.InitializeAsync(createParameters);
} }
// WebGL运行模式 // WebGL运行模式
if (playMode == EPlayMode.WebPlayMode) if (playMode == EPlayMode.WebPlayMode)
{ {
string defaultHostServer = GetHostServerURL(); string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL(); string fallbackHostServer = GetHostServerURL();
var createParameters = new WebPlayModeParameters(); var createParameters = new WebPlayModeParameters();
createParameters.DecryptionServices = new FileStreamDecryption(); createParameters.DecryptionServices = new FileStreamDecryption();
createParameters.BuildinQueryServices = new GameQueryServices(); createParameters.BuildinQueryServices = new GameQueryServices();
createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer); createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
initializationOperation = package.InitializeAsync(createParameters); initializationOperation = package.InitializeAsync(createParameters);
} }
yield return initializationOperation; yield return initializationOperation;
// 如果初始化失败弹出提示界面 // 如果初始化失败弹出提示界面
if (initializationOperation.Status != EOperationStatus.Succeed) if (initializationOperation.Status != EOperationStatus.Succeed)
{ {
Debug.LogWarning($"{initializationOperation.Error}"); Debug.LogWarning($"{initializationOperation.Error}");
PatchEventDefine.InitializeFailed.SendEventMessage(); PatchEventDefine.InitializeFailed.SendEventMessage();
} }
else else
{ {
var version = initializationOperation.PackageVersion; var version = initializationOperation.PackageVersion;
Debug.Log($"Init resource package version : {version}"); Debug.Log($"Init resource package version : {version}");
_machine.ChangeState<FsmUpdatePackageVersion>(); _machine.ChangeState<FsmUpdatePackageVersion>();
} }
} }
/// <summary> /// <summary>
/// 获取资源服务器地址 /// 获取资源服务器地址
/// </summary> /// </summary>
private string GetHostServerURL() private string GetHostServerURL()
{ {
//string hostServerIP = "http://10.0.2.2"; //安卓模拟器地址 //string hostServerIP = "http://10.0.2.2"; //安卓模拟器地址
string hostServerIP = "http://127.0.0.1"; string hostServerIP = "http://127.0.0.1";
string appVersion = "v1.0"; string appVersion = "v1.0";
#if UNITY_EDITOR #if UNITY_EDITOR
if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.Android) if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.Android)
return $"{hostServerIP}/CDN/Android/{appVersion}"; return $"{hostServerIP}/CDN/Android/{appVersion}";
else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.iOS) else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.iOS)
return $"{hostServerIP}/CDN/IPhone/{appVersion}"; return $"{hostServerIP}/CDN/IPhone/{appVersion}";
else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.WebGL) else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.WebGL)
return $"{hostServerIP}/CDN/WebGL/{appVersion}"; return $"{hostServerIP}/CDN/WebGL/{appVersion}";
else else
return $"{hostServerIP}/CDN/PC/{appVersion}"; return $"{hostServerIP}/CDN/PC/{appVersion}";
#else #else
if (Application.platform == RuntimePlatform.Android) if (Application.platform == RuntimePlatform.Android)
return $"{hostServerIP}/CDN/Android/{appVersion}"; return $"{hostServerIP}/CDN/Android/{appVersion}";
else if (Application.platform == RuntimePlatform.IPhonePlayer) else if (Application.platform == RuntimePlatform.IPhonePlayer)
return $"{hostServerIP}/CDN/IPhone/{appVersion}"; return $"{hostServerIP}/CDN/IPhone/{appVersion}";
else if (Application.platform == RuntimePlatform.WebGLPlayer) else if (Application.platform == RuntimePlatform.WebGLPlayer)
return $"{hostServerIP}/CDN/WebGL/{appVersion}"; return $"{hostServerIP}/CDN/WebGL/{appVersion}";
else else
return $"{hostServerIP}/CDN/PC/{appVersion}"; return $"{hostServerIP}/CDN/PC/{appVersion}";
#endif #endif
} }
/// <summary> /// <summary>
/// 远端资源地址查询服务类 /// 远端资源地址查询服务类
/// </summary> /// </summary>
private class RemoteServices : IRemoteServices private class RemoteServices : IRemoteServices
{ {
private readonly string _defaultHostServer; private readonly string _defaultHostServer;
private readonly string _fallbackHostServer; private readonly string _fallbackHostServer;
public RemoteServices(string defaultHostServer, string fallbackHostServer) public RemoteServices(string defaultHostServer, string fallbackHostServer)
{ {
_defaultHostServer = defaultHostServer; _defaultHostServer = defaultHostServer;
_fallbackHostServer = fallbackHostServer; _fallbackHostServer = fallbackHostServer;
} }
string IRemoteServices.GetRemoteMainURL(string fileName) string IRemoteServices.GetRemoteMainURL(string fileName)
{ {
return $"{_defaultHostServer}/{fileName}"; return $"{_defaultHostServer}/{fileName}";
} }
string IRemoteServices.GetRemoteFallbackURL(string fileName) string IRemoteServices.GetRemoteFallbackURL(string fileName)
{ {
return $"{_fallbackHostServer}/{fileName}"; return $"{_fallbackHostServer}/{fileName}";
} }
} }
/// <summary> /// <summary>
/// 资源文件流加载解密类 /// 资源文件流加载解密类
/// </summary> /// </summary>
private class FileStreamDecryption : IDecryptionServices private class FileStreamDecryption : IDecryptionServices
{ {
/// <summary> /// <summary>
/// 同步方式获取解密的资源包对象 /// 同步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放 /// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary> /// </summary>
AssetBundle IDecryptionServices.LoadAssetBundle(DecryptFileInfo fileInfo, out Stream managedStream) AssetBundle IDecryptionServices.LoadAssetBundle(DecryptFileInfo fileInfo, out Stream managedStream)
{ {
BundleStream bundleStream = new BundleStream(fileInfo.FileLoadPath, FileMode.Open, FileAccess.Read, FileShare.Read); BundleStream bundleStream = new BundleStream(fileInfo.FileLoadPath, FileMode.Open, FileAccess.Read, FileShare.Read);
managedStream = bundleStream; managedStream = bundleStream;
return AssetBundle.LoadFromStream(bundleStream, fileInfo.ConentCRC, GetManagedReadBufferSize()); return AssetBundle.LoadFromStream(bundleStream, fileInfo.ConentCRC, GetManagedReadBufferSize());
} }
/// <summary> /// <summary>
/// 异步方式获取解密的资源包对象 /// 异步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放 /// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary> /// </summary>
AssetBundleCreateRequest IDecryptionServices.LoadAssetBundleAsync(DecryptFileInfo fileInfo, out Stream managedStream) AssetBundleCreateRequest IDecryptionServices.LoadAssetBundleAsync(DecryptFileInfo fileInfo, out Stream managedStream)
{ {
BundleStream bundleStream = new BundleStream(fileInfo.FileLoadPath, FileMode.Open, FileAccess.Read, FileShare.Read); BundleStream bundleStream = new BundleStream(fileInfo.FileLoadPath, FileMode.Open, FileAccess.Read, FileShare.Read);
managedStream = bundleStream; managedStream = bundleStream;
return AssetBundle.LoadFromStreamAsync(bundleStream, fileInfo.ConentCRC, GetManagedReadBufferSize()); return AssetBundle.LoadFromStreamAsync(bundleStream, fileInfo.ConentCRC, GetManagedReadBufferSize());
} }
private static uint GetManagedReadBufferSize() private static uint GetManagedReadBufferSize()
{ {
return 1024; return 1024;
} }
} }
/// <summary> /// <summary>
/// 资源文件偏移加载解密类 /// 资源文件偏移加载解密类
/// </summary> /// </summary>
private class FileOffsetDecryption : IDecryptionServices private class FileOffsetDecryption : IDecryptionServices
{ {
/// <summary> /// <summary>
/// 同步方式获取解密的资源包对象 /// 同步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放 /// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary> /// </summary>
AssetBundle IDecryptionServices.LoadAssetBundle(DecryptFileInfo fileInfo, out Stream managedStream) AssetBundle IDecryptionServices.LoadAssetBundle(DecryptFileInfo fileInfo, out Stream managedStream)
{ {
managedStream = null; managedStream = null;
return AssetBundle.LoadFromFile(fileInfo.FileLoadPath, fileInfo.ConentCRC, GetFileOffset()); return AssetBundle.LoadFromFile(fileInfo.FileLoadPath, fileInfo.ConentCRC, GetFileOffset());
} }
/// <summary> /// <summary>
/// 异步方式获取解密的资源包对象 /// 异步方式获取解密的资源包对象
/// 注意:加载流对象在资源包对象释放的时候会自动释放 /// 注意:加载流对象在资源包对象释放的时候会自动释放
/// </summary> /// </summary>
AssetBundleCreateRequest IDecryptionServices.LoadAssetBundleAsync(DecryptFileInfo fileInfo, out Stream managedStream) AssetBundleCreateRequest IDecryptionServices.LoadAssetBundleAsync(DecryptFileInfo fileInfo, out Stream managedStream)
{ {
managedStream = null; managedStream = null;
return AssetBundle.LoadFromFileAsync(fileInfo.FileLoadPath, fileInfo.ConentCRC, GetFileOffset()); return AssetBundle.LoadFromFileAsync(fileInfo.FileLoadPath, fileInfo.ConentCRC, GetFileOffset());
} }
private static ulong GetFileOffset() private static ulong GetFileOffset()
{ {
return 32; return 32;
} }
} }
} }
/// <summary> /// <summary>
@ -220,22 +220,22 @@ internal class FsmInitializePackage : IStateNode
/// </summary> /// </summary>
public class BundleStream : FileStream public class BundleStream : FileStream
{ {
public const byte KEY = 64; 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, FileAccess access, FileShare share) : base(path, mode, access, share)
{ {
} }
public BundleStream(string path, FileMode mode) : base(path, mode) public BundleStream(string path, FileMode mode) : base(path, mode)
{ {
} }
public override int Read(byte[] array, int offset, int count) public override int Read(byte[] array, int offset, int count)
{ {
var index = base.Read(array, offset, count); var index = base.Read(array, offset, count);
for (int i = 0; i < array.Length; i++) for (int i = 0; i < array.Length; i++)
{ {
array[i] ^= KEY; array[i] ^= KEY;
} }
return index; return index;
} }
} }

View File

@ -9,44 +9,44 @@ using YooAsset;
/// </summary> /// </summary>
public class FsmUpdatePackageManifest : IStateNode public class FsmUpdatePackageManifest : IStateNode
{ {
private StateMachine _machine; private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
_machine = machine; _machine = machine;
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
PatchEventDefine.PatchStatesChange.SendEventMessage("更新资源清单!"); PatchEventDefine.PatchStatesChange.SendEventMessage("更新资源清单!");
GameManager.Instance.StartCoroutine(UpdateManifest()); GameManager.Instance.StartCoroutine(UpdateManifest());
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
private IEnumerator UpdateManifest() private IEnumerator UpdateManifest()
{ {
yield return new WaitForSecondsRealtime(0.5f); yield return new WaitForSecondsRealtime(0.5f);
var packageName = (string)_machine.GetBlackboardValue("PackageName"); var packageName = (string)_machine.GetBlackboardValue("PackageName");
var packageVersion = (string)_machine.GetBlackboardValue("PackageVersion"); var packageVersion = (string)_machine.GetBlackboardValue("PackageVersion");
var package = YooAssets.GetPackage(packageName); var package = YooAssets.GetPackage(packageName);
bool savePackageVersion = true; bool savePackageVersion = true;
var operation = package.UpdatePackageManifestAsync(packageVersion, savePackageVersion); var operation = package.UpdatePackageManifestAsync(packageVersion, savePackageVersion);
yield return operation; yield return operation;
if (operation.Status != EOperationStatus.Succeed) if (operation.Status != EOperationStatus.Succeed)
{ {
Debug.LogWarning(operation.Error); Debug.LogWarning(operation.Error);
PatchEventDefine.PatchManifestUpdateFailed.SendEventMessage(); PatchEventDefine.PatchManifestUpdateFailed.SendEventMessage();
yield break; yield break;
} }
else else
{ {
_machine.ChangeState<FsmCreatePackageDownloader>(); _machine.ChangeState<FsmCreatePackageDownloader>();
} }
} }
} }

View File

@ -9,42 +9,42 @@ using YooAsset;
/// </summary> /// </summary>
internal class FsmUpdatePackageVersion : IStateNode internal class FsmUpdatePackageVersion : IStateNode
{ {
private StateMachine _machine; private StateMachine _machine;
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
_machine = machine; _machine = machine;
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
PatchEventDefine.PatchStatesChange.SendEventMessage("获取最新的资源版本 !"); PatchEventDefine.PatchStatesChange.SendEventMessage("获取最新的资源版本 !");
GameManager.Instance.StartCoroutine(UpdatePackageVersion()); GameManager.Instance.StartCoroutine(UpdatePackageVersion());
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
private IEnumerator UpdatePackageVersion() private IEnumerator UpdatePackageVersion()
{ {
yield return new WaitForSecondsRealtime(0.5f); yield return new WaitForSecondsRealtime(0.5f);
var packageName = (string)_machine.GetBlackboardValue("PackageName"); var packageName = (string)_machine.GetBlackboardValue("PackageName");
var package = YooAssets.GetPackage(packageName); var package = YooAssets.GetPackage(packageName);
var operation = package.UpdatePackageVersionAsync(); var operation = package.UpdatePackageVersionAsync();
yield return operation; yield return operation;
if (operation.Status != EOperationStatus.Succeed) if (operation.Status != EOperationStatus.Succeed)
{ {
Debug.LogWarning(operation.Error); Debug.LogWarning(operation.Error);
PatchEventDefine.PackageVersionUpdateFailed.SendEventMessage(); PatchEventDefine.PackageVersionUpdateFailed.SendEventMessage();
} }
else else
{ {
_machine.SetBlackboardValue("PackageVersion", operation.PackageVersion); _machine.SetBlackboardValue("PackageVersion", operation.PackageVersion);
_machine.ChangeState<FsmUpdatePackageManifest>(); _machine.ChangeState<FsmUpdatePackageManifest>();
} }
} }
} }

View File

@ -8,16 +8,16 @@ using UniFramework.Machine;
/// </summary> /// </summary>
internal class FsmUpdaterDone : IStateNode internal class FsmUpdaterDone : IStateNode
{ {
void IStateNode.OnCreate(StateMachine machine) void IStateNode.OnCreate(StateMachine machine)
{ {
} }
void IStateNode.OnEnter() void IStateNode.OnEnter()
{ {
} }
void IStateNode.OnUpdate() void IStateNode.OnUpdate()
{ {
} }
void IStateNode.OnExit() void IStateNode.OnExit()
{ {
} }
} }

View File

@ -8,94 +8,94 @@ using YooAsset;
public class PatchOperation : GameAsyncOperation public class PatchOperation : GameAsyncOperation
{ {
private enum ESteps private enum ESteps
{ {
None, None,
Update, Update,
Done, Done,
} }
private readonly EventGroup _eventGroup = new EventGroup(); private readonly EventGroup _eventGroup = new EventGroup();
private readonly StateMachine _machine; private readonly StateMachine _machine;
private ESteps _steps = ESteps.None; private ESteps _steps = ESteps.None;
public PatchOperation(string packageName, string buildPipeline, EPlayMode playMode) public PatchOperation(string packageName, string buildPipeline, EPlayMode playMode)
{ {
// 注册监听事件 // 注册监听事件
_eventGroup.AddListener<UserEventDefine.UserTryInitialize>(OnHandleEventMessage); _eventGroup.AddListener<UserEventDefine.UserTryInitialize>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserBeginDownloadWebFiles>(OnHandleEventMessage); _eventGroup.AddListener<UserEventDefine.UserBeginDownloadWebFiles>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryUpdatePackageVersion>(OnHandleEventMessage); _eventGroup.AddListener<UserEventDefine.UserTryUpdatePackageVersion>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryUpdatePatchManifest>(OnHandleEventMessage); _eventGroup.AddListener<UserEventDefine.UserTryUpdatePatchManifest>(OnHandleEventMessage);
_eventGroup.AddListener<UserEventDefine.UserTryDownloadWebFiles>(OnHandleEventMessage); _eventGroup.AddListener<UserEventDefine.UserTryDownloadWebFiles>(OnHandleEventMessage);
// 创建状态机 // 创建状态机
_machine = new StateMachine(this); _machine = new StateMachine(this);
_machine.AddNode<FsmInitializePackage>(); _machine.AddNode<FsmInitializePackage>();
_machine.AddNode<FsmUpdatePackageVersion>(); _machine.AddNode<FsmUpdatePackageVersion>();
_machine.AddNode<FsmUpdatePackageManifest>(); _machine.AddNode<FsmUpdatePackageManifest>();
_machine.AddNode<FsmCreatePackageDownloader>(); _machine.AddNode<FsmCreatePackageDownloader>();
_machine.AddNode<FsmDownloadPackageFiles>(); _machine.AddNode<FsmDownloadPackageFiles>();
_machine.AddNode<FsmDownloadPackageOver>(); _machine.AddNode<FsmDownloadPackageOver>();
_machine.AddNode<FsmClearPackageCache>(); _machine.AddNode<FsmClearPackageCache>();
_machine.AddNode<FsmUpdaterDone>(); _machine.AddNode<FsmUpdaterDone>();
_machine.SetBlackboardValue("PackageName", packageName); _machine.SetBlackboardValue("PackageName", packageName);
_machine.SetBlackboardValue("PlayMode", playMode); _machine.SetBlackboardValue("PlayMode", playMode);
_machine.SetBlackboardValue("BuildPipeline", buildPipeline); _machine.SetBlackboardValue("BuildPipeline", buildPipeline);
} }
protected override void OnStart() protected override void OnStart()
{ {
_steps = ESteps.Update; _steps = ESteps.Update;
_machine.Run<FsmInitializePackage>(); _machine.Run<FsmInitializePackage>();
} }
protected override void OnUpdate() protected override void OnUpdate()
{ {
if (_steps == ESteps.None || _steps == ESteps.Done) if (_steps == ESteps.None || _steps == ESteps.Done)
return; return;
if(_steps == ESteps.Update) if(_steps == ESteps.Update)
{ {
_machine.Update(); _machine.Update();
if(_machine.CurrentNode == typeof(FsmUpdaterDone).FullName) if(_machine.CurrentNode == typeof(FsmUpdaterDone).FullName)
{ {
_eventGroup.RemoveAllListener(); _eventGroup.RemoveAllListener();
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
_steps = ESteps.Done; _steps = ESteps.Done;
} }
} }
} }
protected override void OnAbort() protected override void OnAbort()
{ {
} }
/// <summary> /// <summary>
/// 接收事件 /// 接收事件
/// </summary> /// </summary>
private void OnHandleEventMessage(IEventMessage message) private void OnHandleEventMessage(IEventMessage message)
{ {
if (message is UserEventDefine.UserTryInitialize) if (message is UserEventDefine.UserTryInitialize)
{ {
_machine.ChangeState<FsmInitializePackage>(); _machine.ChangeState<FsmInitializePackage>();
} }
else if (message is UserEventDefine.UserBeginDownloadWebFiles) else if (message is UserEventDefine.UserBeginDownloadWebFiles)
{ {
_machine.ChangeState<FsmDownloadPackageFiles>(); _machine.ChangeState<FsmDownloadPackageFiles>();
} }
else if (message is UserEventDefine.UserTryUpdatePackageVersion) else if (message is UserEventDefine.UserTryUpdatePackageVersion)
{ {
_machine.ChangeState<FsmUpdatePackageVersion>(); _machine.ChangeState<FsmUpdatePackageVersion>();
} }
else if (message is UserEventDefine.UserTryUpdatePatchManifest) else if (message is UserEventDefine.UserTryUpdatePatchManifest)
{ {
_machine.ChangeState<FsmUpdatePackageManifest>(); _machine.ChangeState<FsmUpdatePackageManifest>();
} }
else if (message is UserEventDefine.UserTryDownloadWebFiles) else if (message is UserEventDefine.UserTryDownloadWebFiles)
{ {
_machine.ChangeState<FsmCreatePackageDownloader>(); _machine.ChangeState<FsmCreatePackageDownloader>();
} }
else else
{ {
throw new System.NotImplementedException($"{message.GetType()}"); throw new System.NotImplementedException($"{message.GetType()}");
} }
} }
} }

View File

@ -7,178 +7,178 @@ using UniFramework.Event;
public class PatchWindow : MonoBehaviour public class PatchWindow : MonoBehaviour
{ {
/// <summary> /// <summary>
/// 对话框封装类 /// 对话框封装类
/// </summary> /// </summary>
private class MessageBox private class MessageBox
{ {
private GameObject _cloneObject; private GameObject _cloneObject;
private Text _content; private Text _content;
private Button _btnOK; private Button _btnOK;
private System.Action _clickOK; private System.Action _clickOK;
public bool ActiveSelf public bool ActiveSelf
{ {
get get
{ {
return _cloneObject.activeSelf; return _cloneObject.activeSelf;
} }
} }
public void Create(GameObject cloneObject) public void Create(GameObject cloneObject)
{ {
_cloneObject = cloneObject; _cloneObject = cloneObject;
_content = cloneObject.transform.Find("txt_content").GetComponent<Text>(); _content = cloneObject.transform.Find("txt_content").GetComponent<Text>();
_btnOK = cloneObject.transform.Find("btn_ok").GetComponent<Button>(); _btnOK = cloneObject.transform.Find("btn_ok").GetComponent<Button>();
_btnOK.onClick.AddListener(OnClickYes); _btnOK.onClick.AddListener(OnClickYes);
} }
public void Show(string content, System.Action clickOK) public void Show(string content, System.Action clickOK)
{ {
_content.text = content; _content.text = content;
_clickOK = clickOK; _clickOK = clickOK;
_cloneObject.SetActive(true); _cloneObject.SetActive(true);
_cloneObject.transform.SetAsLastSibling(); _cloneObject.transform.SetAsLastSibling();
} }
public void Hide() public void Hide()
{ {
_content.text = string.Empty; _content.text = string.Empty;
_clickOK = null; _clickOK = null;
_cloneObject.SetActive(false); _cloneObject.SetActive(false);
} }
private void OnClickYes() private void OnClickYes()
{ {
_clickOK?.Invoke(); _clickOK?.Invoke();
Hide(); Hide();
} }
} }
private readonly EventGroup _eventGroup = new EventGroup(); private readonly EventGroup _eventGroup = new EventGroup();
private readonly List<MessageBox> _msgBoxList = new List<MessageBox>(); private readonly List<MessageBox> _msgBoxList = new List<MessageBox>();
// UGUI相关 // UGUI相关
private GameObject _messageBoxObj; private GameObject _messageBoxObj;
private Slider _slider; private Slider _slider;
private Text _tips; private Text _tips;
void Awake() void Awake()
{ {
_slider = transform.Find("UIWindow/Slider").GetComponent<Slider>(); _slider = transform.Find("UIWindow/Slider").GetComponent<Slider>();
_tips = transform.Find("UIWindow/Slider/txt_tips").GetComponent<Text>(); _tips = transform.Find("UIWindow/Slider/txt_tips").GetComponent<Text>();
_tips.text = "Initializing the game world !"; _tips.text = "Initializing the game world !";
_messageBoxObj = transform.Find("UIWindow/MessgeBox").gameObject; _messageBoxObj = transform.Find("UIWindow/MessgeBox").gameObject;
_messageBoxObj.SetActive(false); _messageBoxObj.SetActive(false);
_eventGroup.AddListener<PatchEventDefine.InitializeFailed>(OnHandleEventMessage); _eventGroup.AddListener<PatchEventDefine.InitializeFailed>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.PatchStatesChange>(OnHandleEventMessage); _eventGroup.AddListener<PatchEventDefine.PatchStatesChange>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.FoundUpdateFiles>(OnHandleEventMessage); _eventGroup.AddListener<PatchEventDefine.FoundUpdateFiles>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.DownloadProgressUpdate>(OnHandleEventMessage); _eventGroup.AddListener<PatchEventDefine.DownloadProgressUpdate>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.PackageVersionUpdateFailed>(OnHandleEventMessage); _eventGroup.AddListener<PatchEventDefine.PackageVersionUpdateFailed>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.PatchManifestUpdateFailed>(OnHandleEventMessage); _eventGroup.AddListener<PatchEventDefine.PatchManifestUpdateFailed>(OnHandleEventMessage);
_eventGroup.AddListener<PatchEventDefine.WebFileDownloadFailed>(OnHandleEventMessage); _eventGroup.AddListener<PatchEventDefine.WebFileDownloadFailed>(OnHandleEventMessage);
} }
void OnDestroy() void OnDestroy()
{ {
_eventGroup.RemoveAllListener(); _eventGroup.RemoveAllListener();
} }
/// <summary> /// <summary>
/// 接收事件 /// 接收事件
/// </summary> /// </summary>
private void OnHandleEventMessage(IEventMessage message) private void OnHandleEventMessage(IEventMessage message)
{ {
if (message is PatchEventDefine.InitializeFailed) if (message is PatchEventDefine.InitializeFailed)
{ {
System.Action callback = () => System.Action callback = () =>
{ {
UserEventDefine.UserTryInitialize.SendEventMessage(); UserEventDefine.UserTryInitialize.SendEventMessage();
}; };
ShowMessageBox($"Failed to initialize package !", callback); ShowMessageBox($"Failed to initialize package !", callback);
} }
else if (message is PatchEventDefine.PatchStatesChange) else if (message is PatchEventDefine.PatchStatesChange)
{ {
var msg = message as PatchEventDefine.PatchStatesChange; var msg = message as PatchEventDefine.PatchStatesChange;
_tips.text = msg.Tips; _tips.text = msg.Tips;
} }
else if (message is PatchEventDefine.FoundUpdateFiles) else if (message is PatchEventDefine.FoundUpdateFiles)
{ {
var msg = message as PatchEventDefine.FoundUpdateFiles; var msg = message as PatchEventDefine.FoundUpdateFiles;
System.Action callback = () => System.Action callback = () =>
{ {
UserEventDefine.UserBeginDownloadWebFiles.SendEventMessage(); UserEventDefine.UserBeginDownloadWebFiles.SendEventMessage();
}; };
float sizeMB = msg.TotalSizeBytes / 1048576f; float sizeMB = msg.TotalSizeBytes / 1048576f;
sizeMB = Mathf.Clamp(sizeMB, 0.1f, float.MaxValue); sizeMB = Mathf.Clamp(sizeMB, 0.1f, float.MaxValue);
string totalSizeMB = sizeMB.ToString("f1"); string totalSizeMB = sizeMB.ToString("f1");
ShowMessageBox($"Found update patch files, Total count {msg.TotalCount} Total szie {totalSizeMB}MB", callback); ShowMessageBox($"Found update patch files, Total count {msg.TotalCount} Total szie {totalSizeMB}MB", callback);
} }
else if (message is PatchEventDefine.DownloadProgressUpdate) else if (message is PatchEventDefine.DownloadProgressUpdate)
{ {
var msg = message as PatchEventDefine.DownloadProgressUpdate; var msg = message as PatchEventDefine.DownloadProgressUpdate;
_slider.value = (float)msg.CurrentDownloadCount / msg.TotalDownloadCount; _slider.value = (float)msg.CurrentDownloadCount / msg.TotalDownloadCount;
string currentSizeMB = (msg.CurrentDownloadSizeBytes / 1048576f).ToString("f1"); string currentSizeMB = (msg.CurrentDownloadSizeBytes / 1048576f).ToString("f1");
string totalSizeMB = (msg.TotalDownloadSizeBytes / 1048576f).ToString("f1"); string totalSizeMB = (msg.TotalDownloadSizeBytes / 1048576f).ToString("f1");
_tips.text = $"{msg.CurrentDownloadCount}/{msg.TotalDownloadCount} {currentSizeMB}MB/{totalSizeMB}MB"; _tips.text = $"{msg.CurrentDownloadCount}/{msg.TotalDownloadCount} {currentSizeMB}MB/{totalSizeMB}MB";
} }
else if (message is PatchEventDefine.PackageVersionUpdateFailed) else if (message is PatchEventDefine.PackageVersionUpdateFailed)
{ {
System.Action callback = () => System.Action callback = () =>
{ {
UserEventDefine.UserTryUpdatePackageVersion.SendEventMessage(); UserEventDefine.UserTryUpdatePackageVersion.SendEventMessage();
}; };
ShowMessageBox($"Failed to update static version, please check the network status.", callback); ShowMessageBox($"Failed to update static version, please check the network status.", callback);
} }
else if (message is PatchEventDefine.PatchManifestUpdateFailed) else if (message is PatchEventDefine.PatchManifestUpdateFailed)
{ {
System.Action callback = () => System.Action callback = () =>
{ {
UserEventDefine.UserTryUpdatePatchManifest.SendEventMessage(); UserEventDefine.UserTryUpdatePatchManifest.SendEventMessage();
}; };
ShowMessageBox($"Failed to update patch manifest, please check the network status.", callback); ShowMessageBox($"Failed to update patch manifest, please check the network status.", callback);
} }
else if (message is PatchEventDefine.WebFileDownloadFailed) else if (message is PatchEventDefine.WebFileDownloadFailed)
{ {
var msg = message as PatchEventDefine.WebFileDownloadFailed; var msg = message as PatchEventDefine.WebFileDownloadFailed;
System.Action callback = () => System.Action callback = () =>
{ {
UserEventDefine.UserTryDownloadWebFiles.SendEventMessage(); UserEventDefine.UserTryDownloadWebFiles.SendEventMessage();
}; };
ShowMessageBox($"Failed to download file : {msg.FileName}", callback); ShowMessageBox($"Failed to download file : {msg.FileName}", callback);
} }
else else
{ {
throw new System.NotImplementedException($"{message.GetType()}"); throw new System.NotImplementedException($"{message.GetType()}");
} }
} }
/// <summary> /// <summary>
/// 显示对话框 /// 显示对话框
/// </summary> /// </summary>
private void ShowMessageBox(string content, System.Action ok) private void ShowMessageBox(string content, System.Action ok)
{ {
// 尝试获取一个可用的对话框 // 尝试获取一个可用的对话框
MessageBox msgBox = null; MessageBox msgBox = null;
for (int i = 0; i < _msgBoxList.Count; i++) for (int i = 0; i < _msgBoxList.Count; i++)
{ {
var item = _msgBoxList[i]; var item = _msgBoxList[i];
if (item.ActiveSelf == false) if (item.ActiveSelf == false)
{ {
msgBox = item; msgBox = item;
break; break;
} }
} }
// 如果没有可用的对话框,则创建一个新的对话框 // 如果没有可用的对话框,则创建一个新的对话框
if (msgBox == null) if (msgBox == null)
{ {
msgBox = new MessageBox(); msgBox = new MessageBox();
var cloneObject = GameObject.Instantiate(_messageBoxObj, _messageBoxObj.transform.parent); var cloneObject = GameObject.Instantiate(_messageBoxObj, _messageBoxObj.transform.parent);
msgBox.Create(cloneObject); msgBox.Create(cloneObject);
_msgBoxList.Add(msgBox); _msgBoxList.Add(msgBox);
} }
// 显示对话框 // 显示对话框
msgBox.Show(content, ok); msgBox.Show(content, ok);
} }
} }

View File

@ -5,14 +5,14 @@ using UnityEngine.UI;
public class UIAboutWindow : MonoBehaviour public class UIAboutWindow : MonoBehaviour
{ {
private void Awake() private void Awake()
{ {
var maskBtn = this.transform.Find("mask").GetComponent<Button>(); var maskBtn = this.transform.Find("mask").GetComponent<Button>();
maskBtn.onClick.AddListener(OnClicMaskBtn); maskBtn.onClick.AddListener(OnClicMaskBtn);
} }
private void OnClicMaskBtn() private void OnClicMaskBtn()
{ {
GameObject.Destroy(this.gameObject); GameObject.Destroy(this.gameObject);
} }
} }

View File

@ -6,48 +6,48 @@ using UniFramework.Event;
public class UIBattleWindow : MonoBehaviour public class UIBattleWindow : MonoBehaviour
{ {
private readonly EventGroup _eventGroup = new EventGroup(); private readonly EventGroup _eventGroup = new EventGroup();
private GameObject _overView; private GameObject _overView;
private Text _scoreLabel; private Text _scoreLabel;
private void Awake() private void Awake()
{ {
_overView = this.transform.Find("OverView").gameObject; _overView = this.transform.Find("OverView").gameObject;
_scoreLabel = this.transform.Find("ScoreView/Score").GetComponent<Text>(); _scoreLabel = this.transform.Find("ScoreView/Score").GetComponent<Text>();
_scoreLabel.text = "Score : 0"; _scoreLabel.text = "Score : 0";
var restartBtn = this.transform.Find("OverView/Restart").GetComponent<Button>(); var restartBtn = this.transform.Find("OverView/Restart").GetComponent<Button>();
restartBtn.onClick.AddListener(OnClickRestartBtn); restartBtn.onClick.AddListener(OnClickRestartBtn);
var homeBtn = this.transform.Find("OverView/Home").GetComponent<Button>(); var homeBtn = this.transform.Find("OverView/Home").GetComponent<Button>();
homeBtn.onClick.AddListener(OnClickHomeBtn); homeBtn.onClick.AddListener(OnClickHomeBtn);
_eventGroup.AddListener<BattleEventDefine.ScoreChange>(OnHandleEventMessage); _eventGroup.AddListener<BattleEventDefine.ScoreChange>(OnHandleEventMessage);
_eventGroup.AddListener<BattleEventDefine.GameOver>(OnHandleEventMessage); _eventGroup.AddListener<BattleEventDefine.GameOver>(OnHandleEventMessage);
} }
private void OnDestroy() private void OnDestroy()
{ {
_eventGroup.RemoveAllListener(); _eventGroup.RemoveAllListener();
} }
private void OnClickRestartBtn() private void OnClickRestartBtn()
{ {
SceneEventDefine.ChangeToBattleScene.SendEventMessage(); SceneEventDefine.ChangeToBattleScene.SendEventMessage();
} }
private void OnClickHomeBtn() private void OnClickHomeBtn()
{ {
SceneEventDefine.ChangeToHomeScene.SendEventMessage(); SceneEventDefine.ChangeToHomeScene.SendEventMessage();
} }
private void OnHandleEventMessage(IEventMessage message) private void OnHandleEventMessage(IEventMessage message)
{ {
if(message is BattleEventDefine.ScoreChange) if(message is BattleEventDefine.ScoreChange)
{ {
var msg = message as BattleEventDefine.ScoreChange; var msg = message as BattleEventDefine.ScoreChange;
_scoreLabel.text = $"Score : {msg.CurrentScores}"; _scoreLabel.text = $"Score : {msg.CurrentScores}";
} }
else if(message is BattleEventDefine.GameOver) else if(message is BattleEventDefine.GameOver)
{ {
_overView.SetActive(true); _overView.SetActive(true);
} }
} }
} }

View File

@ -5,40 +5,40 @@ using UnityEngine.UI;
public class UIHomeWindow : MonoBehaviour public class UIHomeWindow : MonoBehaviour
{ {
private Text _version; private Text _version;
private GameObject _aboutView; private GameObject _aboutView;
private void Awake() private void Awake()
{ {
_version = this.transform.Find("version").GetComponent<Text>(); _version = this.transform.Find("version").GetComponent<Text>();
_aboutView = this.transform.Find("AboutView").gameObject; _aboutView = this.transform.Find("AboutView").gameObject;
var loginBtn = this.transform.Find("Start").GetComponent<Button>(); var loginBtn = this.transform.Find("Start").GetComponent<Button>();
loginBtn.onClick.AddListener(OnClickLoginBtn); loginBtn.onClick.AddListener(OnClickLoginBtn);
var aboutBtn = this.transform.Find("About").GetComponent<Button>(); var aboutBtn = this.transform.Find("About").GetComponent<Button>();
aboutBtn.onClick.AddListener(OnClicAboutBtn); aboutBtn.onClick.AddListener(OnClicAboutBtn);
var maskBtn = this.transform.Find("AboutView/mask").GetComponent<Button>(); var maskBtn = this.transform.Find("AboutView/mask").GetComponent<Button>();
maskBtn.onClick.AddListener(OnClickMaskBtn); maskBtn.onClick.AddListener(OnClickMaskBtn);
} }
private void Start() private void Start()
{ {
var package = YooAsset.YooAssets.GetPackage("DefaultPackage"); var package = YooAsset.YooAssets.GetPackage("DefaultPackage");
_version.text = "Ver : " + package.GetPackageVersion(); _version.text = "Ver : " + package.GetPackageVersion();
} }
private void OnClickLoginBtn() private void OnClickLoginBtn()
{ {
SceneEventDefine.ChangeToBattleScene.SendEventMessage(); SceneEventDefine.ChangeToBattleScene.SendEventMessage();
} }
private void OnClicAboutBtn() private void OnClicAboutBtn()
{ {
_aboutView.SetActive(true); _aboutView.SetActive(true);
} }
private void OnClickMaskBtn() private void OnClickMaskBtn()
{ {
_aboutView.SetActive(false); _aboutView.SetActive(false);
} }
} }

View File

@ -6,34 +6,34 @@ using UniFramework.Utility;
public class UILoadingWindow : MonoBehaviour public class UILoadingWindow : MonoBehaviour
{ {
private Text _info; private Text _info;
private int _countdown; private int _countdown;
private UniTimer _timer = UniTimer.CreatePepeatTimer(0, 0.2f); private UniTimer _timer = UniTimer.CreatePepeatTimer(0, 0.2f);
private void Awake() private void Awake()
{ {
_info = this.transform.Find("info").GetComponent<Text>(); _info = this.transform.Find("info").GetComponent<Text>();
} }
private void Start() private void Start()
{ {
_info.text = "Loading"; _info.text = "Loading";
_timer.Reset(); _timer.Reset();
_countdown = 0; _countdown = 0;
} }
private void Update() private void Update()
{ {
if(_timer.Update(Time.deltaTime)) if(_timer.Update(Time.deltaTime))
{ {
_countdown++; _countdown++;
if (_countdown > 6) if (_countdown > 6)
_countdown = 0; _countdown = 0;
string tips = "Loading"; string tips = "Loading";
for(int i=0; i<_countdown; i++) for(int i=0; i<_countdown; i++)
{ {
tips += "."; tips += ".";
} }
_info.text = tips; _info.text = tips;
} }
} }
} }

View File

@ -8,7 +8,7 @@ using UnityEngine;
public class BuildinFileManifest : ScriptableObject public class BuildinFileManifest : ScriptableObject
{ {
[Serializable] [Serializable]
public class Element public class Element
{ {
public string PackageName; public string PackageName;
public string FileName; public string FileName;

View File

@ -1,8 +1,8 @@
 
public class StreamingAssetsDefine public class StreamingAssetsDefine
{ {
/// <summary> /// <summary>
/// 根目录名称保持和YooAssets资源系统一致 /// 根目录名称保持和YooAssets资源系统一致
/// </summary> /// </summary>
public const string RootFolderName = "yoo"; public const string RootFolderName = "yoo";
} }