AssetBundle(创建打包)入门学习(基于Unity2017) (已看)

  分组策略

  1. 逻辑实体分组
  2. 按照类型分组
  3. 按照使用分组

  分组策略----总结

  1. 把经常更新的资源放在一个单独的包里面,跟不经常更新的包分离
  2. 把需要同时加载的资源放在一个包里面
  3. 可以把其他包共享的资源放在一个单独的包里面
  4. 把一些需要同时加载的小资源打包成一个包
  5. 如果对于同一个资源有两个版本,可以考虑通过后缀来区分

 

  BuildAssetBundleOptions

  1. BuildAssetBundleOptions.None: 使用LZMA算法压缩,压缩的包更小,但是加载时间更长.使用之前需要整体压缩.一旦被解压,这个包会使用LZ4重新压缩.使用资源的时候不需要整体解压.在下载的时候可以使用LZMA算法,一旦
  2. BuildAssetBundleOptions.UncompressedAssetBundle: 不压缩,包大,加载快
  3. BuildAssetBundleOptions.ChunkBasedCompression: 使用LZ4压缩,压缩率没有LZMA高,但是我们可以加载指定资源而不用解压全部
  1. ManifestFileVersion:
  2. CRC:
  3. AssetBundleManifest:
  4. AssetBundleInfo:
  5. Info_0:
  6. Name: share.untiy3d
  7. Dependencies: {}
  8. Info_1:
  9. Name: capsulewall.unity3d
  10. Dependencies:
  11. Dependency_0: share.unity3d
  12. Info_2:
  13. Name: cubewall.unity3d
  14. Dependencies:
  15. Dependency_0: share.unity3d

AssetBundles.manifest

  文件校验

  CRC MD5 SHA1
相同点:
  CRC、MD5、SHA1都是通过对数据进行计算,来生成一个校验值,该校验值用来校验数据的完整性。
不同点:

  1. 算法不同。CRC采用多项式除法,MD5和SHA1使用的是替换、轮转等方法;
  2. 校验值的长度不同。CRC校验位的长度跟其多项式有关系,一般为16位或32位;MD5是16个字节(128位);SHA1是20个字节(160位);
  3. 校验值的称呼不同。CRC一般叫做CRC值;MD5和SHA1一般叫做哈希值(Hash)或散列值;
  4. 安全性不同。这里的安全性是指检错的能力,即数据的错误能通过校验位检测出来。CRC的安全性跟多项式有很大关系,相对于MD5和SHA1要弱很多;MD5的安全性很高,不过大概在04年的时候被山东大学的王小云破解了;SHA1的安全性最高。
  5. 效率不同,CRC的计算效率很高;MD5和SHA1比较慢。
  6. 用途不同。CRC一般用作通信数据的校验;MD5和SHA1用于安全(Security)领域,比如文件校验、数字签名等。

Asset: https://docs.unity3d.com/Manual/AssetWorkflow.html

  An Asset is a representation of any item you can use in your game or Project.

  An Asset may come from a file created outside of Unity, such as a 3D Model, an audio file, an image, or any of the other file types that Unity supports.

  There are also some Asset types that you can create in Unity, such as a ProBuilder Mesh , an Animator Controller , an Audio Mixer, or a Render Texture.

SpecialFolders: https://docs.unity3d.com/Manual/SpecialFolders.html

  • Asset: The Assets folder is the main folder that contains the Assets used by a Unity project.
  • Editor: Scripts placed in a folder called Editor are treated as Editor scripts rather than runtime scripts.These scripts add functionality to the Editor during development, and are not available in builds at runtime.
  • Editor Default Resources: Editor scripts can make use of Asset files loaded-on-demand using the EditorGUIUtility.Load function. This function looks for the Asset files in a folder called Editor Default Resources. You can only have one
  • Gizmos:  You can only have one Gizmos folder and it must be placed in the root of the Project.
  • Plug-ins: You can only have one Plugins folder and it must be placed in the root of the Project; directly within the Assets folders;
  • Resources: You can load Assets on-demand from a script instead of creating instances of Assets in a Scene for use in gameplay. You do this by placing the Assets in a folder called Resources
  • Standard Assets: When you import a Standard Asset package the Assets are placed in a folder called Standard Assets.
  • StreamingAssets: Place a file in a folder called StreamingAssets,so it is copied unchanged to the target machine, where it is then available from a specific folder.
  • Hidden Assets: During the import process, Unity completely ignores the following files and folders in the Assets folder
  1. Hidden folders
  2. Files and folders which start with '.'
  3. Files and folders which end with '~'
  4. Files and folders named cvs
  5. Files with the extension .tmp

StreamingAssets: https://docs.unity3d.com/Manual/StreamingAssets.html

  Any files placed in a folder called StreamingAssets (case-sensitive) in a Unity project will be copied verbatim to a particular folder on the target machine

    On a desktop computer:  path = Application.dataPath + "/StreamingAssets"

    On iOS, use:  path = Application.dataPath + "/Raw"

    On Android, use:  path = "jar:file://" + Application.dataPath + "!/assets/";

AssetBundles: https://docs.unity3d.com/Manual/AssetBundlesIntro.html

  AssetBundle Workflow  

    An AssetBundle is an archive file containing platform specific Assets (Models, Textures, Prefabs, Audio clips, and even entire Scenes) that can be loaded at runtime.

    AssetBundles can express dependencies between each other; e.g. a material in AssetBundle A can reference a texture in AssetBundle B.

    For efficient delivery over networks, AssetBundles can be compressed with a choice of built-in algorithms depending on use case requirements (LZMA and LZ4).

What's in an AssetBundle?

    AssetBundle can refer to two different, but related things.

      First is the actual file on disk. This we call the AssetBundle archive, or just archive for short in this document. The archive can be thought of as a container, like a folder, that holds additional files inside of it. These additional files consist of two types; the serialized file and resource files. The serialized file contains your assets broken out into their individual objects and written out to this single file. The resource files are just chunks of binary data stored separately for certain assets (textures and audio) to allow us to load them from disk on another thread efficiently.

      Second is the actual AssetBundle object you interact with via code to load assets from a specific archive. This object contains a map of all the file paths of the assets you added to this archive to the objects that belong to that asset that need to be loaded when you ask for it.

  1. public class CRC32 {
  2. static UInt32[] crcTable =
  3. {
  4. 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
  5. 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
  6. 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
  7. 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
  8. 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
  9. 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
  10. 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
  11. 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
  12. 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
  13. 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
  14. 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
  15. 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
  16. 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
  17. 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
  18. 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
  19. 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
  20. 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
  21. 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
  22. 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
  23. 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
  24. 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
  25. 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
  26. 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
  27. 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
  28. 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
  29. 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
  30. 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
  31. 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
  32. 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
  33. 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
  34. 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
  35. 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
  36. };
  37.  
  38. public static uint GetCRC32(string msg) {
  39. byte[] bytes = System.Text.Encoding.UTF8.GetBytes(msg);
  40. uint iCount = (uint)bytes.Length;
  41. uint crc = 0xFFFFFFFF;
  42.  
  43. for (uint i = ; i < iCount; i++) {
  44. crc = (crc << ) ^ crcTable[(crc >> ) ^ bytes[i]];
  45. }
  46.  
  47. return crc;
  48. }
  49. }

  Preparing Assets for AssetBundles

  Building AssetBundles

  AssetBundle Dependencies

    AssetBundles can become dependent on other AssetBundles if one or more of the UnityEngine.Objects contains a reference to a UnityEngine.Object located in another bundle. A dependency does not occur if the UnityEngine.Object contains a reference to a UnityEngine.Object that is not contained in any AssetBundle. In this case, a copy of the object that the bundle would be dependent on is copied into the bundle when you build the AssetBundles. If multiple objects in multiple bundles contain a reference to the same object that isn’t assigned to a bundle, every bundle that would have a dependency on that object will make its own copy of the object and package it into the built AssetBundle.

    Should an AssetBundle contain a dependency, it is important that the bundles that contain those dependencies are loaded before the object you’re attempting to instantiate is loaded. Unity will not attempt to automatically load dependencies.

    Consider the following example, a Material in Bundle 1 references a Texture in Bundle 2:

In this example, before loading the Material from Bundle 1, you would need to load Bundle 2 into memory. It does not matter which order you load Bundle 1 and Bundle 2, the important takeaway is that Bundle 2 is loaded before loading the Material from Bundle 1.

  Using AssetBundles Natively

  Patching with AssetBundles

  Troubleshooting

  Unity Asset Bundle Browser tool

AssetBundle框架设计_理论篇 (已看)

AssetBundle框架设计_框架篇 (已看)

AB打包分类  

  按类型  

  按场景  包名称 = "场景名称/功能文件夹名"

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using System.IO;
  6.  
  7. namespace ABFramework {
  8.  
  9. /// <summary>
  10. /// 1. 定义需要打包资源的文件夹根目录
  11. /// 2. 遍历每个"场景"文件夹(目录)
  12. /// a. 遍历本场景目录下所有的目录或者文件
  13. /// 如果是目录,则继续"递归"访问里面的文件,直到定位到文件
  14. /// b. 找到文件,则使用AssetImporter类,标记"包名"与"后缀名"
  15. /// </summary>
  16. public class AutoSetABName {
  17.  
  18. /// <summary>
  19. /// 设置AB包名称
  20. /// </summary>
  21. [MenuItem("AssetBundleTools/Set AB Name")]
  22. public static void SetABName() {
  23.  
  24. AssetDatabase.RemoveUnusedAssetBundleNames();
  25.  
  26. string abResPath = string.Empty;
  27. abResPath = PathTools.GetABResourcesPath();
  28.  
  29. DirectoryInfo[] dirScenesArray = null; // 根目录下的所有一级子目录
  30.  
  31. DirectoryInfo dirTempInfo = new DirectoryInfo(abResPath);
  32. dirScenesArray = dirTempInfo.GetDirectories();
  33.  
  34. foreach (var item in dirScenesArray) {
  35. string tempSceneDir = abResPath + "/" + item.Name; // 全路径
  36.  
  37. //DirectoryInfo tempSceneDirInfo = new DirectoryInfo(tempSceneDir);
  38.  
  39. int tempIndex = tempSceneDir.LastIndexOf("/");
  40. string tempSceneName = tempSceneDir.Substring(tempIndex + ); // 场景名称
  41.  
  42. JudgeDirOrFileRecursive(item, tempSceneName);
  43. }
  44.  
  45. AssetDatabase.Refresh();
  46.  
  47. Debug.Log("AssetBundle 本次操作设置标记完成!");
  48. }
  49.  
  50. private static void JudgeDirOrFileRecursive(FileSystemInfo fileSystemInfo, string sceneName) {
  51. if (!fileSystemInfo.Exists) {
  52. Debug.LogError("文件或目录名称: " + fileSystemInfo + "不存在,检查");
  53. return;
  54. }
  55.  
  56. DirectoryInfo dirInfo = fileSystemInfo as DirectoryInfo; // 文件信息转换为目录信息
  57. FileSystemInfo[] fileSystemInfoArr = dirInfo.GetFileSystemInfos();
  58.  
  59. foreach (var item in fileSystemInfoArr) {
  60. FileInfo fileInfo = item as FileInfo;
  61.  
  62. if (fileInfo != null) {
  63. SetFileABName(fileInfo, sceneName); // 设置文件的AB名
  64. } else {
  65. JudgeDirOrFileRecursive(item, sceneName); // 递归目录
  66. }
  67. }
  68. }
  69.  
  70. /// <summary>
  71. /// 对指定的文件设置AB包名
  72. /// </summary>
  73. private static void SetFileABName(FileInfo fileInfo, string sceneName) {
  74. string abName = string.Empty;
  75. string assetFilePath = string.Empty; // 文件路径(相对路径)
  76.  
  77. if (fileInfo.Extension == ".meta") {
  78. return;
  79. }
  80.  
  81. abName = GetABName(fileInfo, sceneName);
  82.  
  83. // 获取资源文件的相对路径
  84. int tempIndex = fileInfo.FullName.IndexOf("Assets");
  85. assetFilePath = fileInfo.FullName.Substring(tempIndex);
  86.  
  87. AssetImporter tempImporter = AssetImporter.GetAtPath(assetFilePath);
  88. tempImporter.assetBundleName = abName;
  89.  
  90. //Debug.Log("assetFilePath: " + assetFilePath);
  91. //Debug.Log("abName: " + abName);
  92.  
  93. if (fileInfo.Extension == ".unity") {
  94. tempImporter.assetBundleVariant = "u3d";
  95. } else {
  96. tempImporter.assetBundleVariant = "ab";
  97. }
  98. //Debug.Log(fileInfo.FullName);
  99. //Debug.Log(tempImporter.assetBundleVariant);
  100.  
  101. //if (fileInfo.Extension == ".unity") {
  102. // // 定义AB包的扩展名
  103.  
  104. //}
  105.  
  106. //Debug.Log(assetFilePath);
  107.  
  108. //AssetImporter tempImporter = AssetImporter.GetAtPath(fileInfo.FullName);
  109. //Debug.Log(tempImporter);
  110. //Debug.Log(tempImporter.)
  111. }
  112.  
  113. /// <summary>
  114. /// 获取AB包的名称
  115. ///
  116. /// AB包形成规则
  117. /// 文件AB包名称 = "所在二级目录名称"(场景名称) + "三级目录名称"(下一级的"类型名称")
  118. /// </summary>
  119. private static string GetABName(FileInfo fileInfo, string sceneName) {
  120. string abName = string.Empty;
  121.  
  122. // Win路径
  123. string tempWinPath = fileInfo.FullName;
  124. // Unity路径
  125. string tempUnityPath = tempWinPath.Replace("\\", "/");
  126. // 定位"场景名称"后面字符的位置
  127. int tempSceneNazmePos = tempUnityPath.IndexOf(sceneName) + sceneName.Length;
  128. // AB包中的"类型名称"所在区域
  129. string abFileNameArea = tempUnityPath.Substring(tempSceneNazmePos + );
  130.  
  131. if (abFileNameArea.Contains("/")) {
  132. string[] tempStrArr = abFileNameArea.Split('/');
  133. abName = sceneName + "/" + tempStrArr[];
  134. } else {
  135. // .unity AB包名
  136. abName = sceneName + "/" + sceneName;
  137. }
  138.  
  139. return abName;
  140. }
  141. }
  142. }

AutoSetABName

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using System.IO;
  6.  
  7. namespace ABFramework {
  8.  
  9. public class BuildAssetBundle {
  10.  
  11. [MenuItem("AssetBundleTools/BuildAllAssetBundles")]
  12. public static void BuildAllAB() {
  13. string abOutPathDir = string.Empty;
  14.  
  15. abOutPathDir = PathTools.GetABOutputPath();
  16.  
  17. if (!Directory.Exists(abOutPathDir)) {
  18. Directory.CreateDirectory(abOutPathDir);
  19. }
  20.  
  21. BuildPipeline.BuildAssetBundles(abOutPathDir, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
  22. }
  23. }
  24. }

BuildAssetBundle

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using System.IO;
  6.  
  7. namespace ABFramework {
  8.  
  9. public class DeleteAssetBundle {
  10.  
  11. [MenuItem("AssetBundleTools/DeleteAllAssetBundle")]
  12. public static void DelAssetBundle() {
  13. string deleteDir = string.Empty;
  14.  
  15. deleteDir = PathTools.GetABOutputPath();
  16.  
  17. if (!string.IsNullOrEmpty(deleteDir)) {
  18. Directory.Delete(deleteDir, true);
  19. File.Delete(deleteDir + " .meta");
  20. AssetDatabase.Refresh();
  21. }
  22. }
  23. }
  24. }

DeleteAssetBundle

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. /* 委托定义 */
  8. public delegate void ABLoadComplete(string abName);
  9.  
  10. public class ABDefine {
  11. public static readonly string ASSETBUNDLEMANIFEST = "AssetBundleManifest";
  12. }
  13. }

ABDefine

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PathTools {
  6.  
  7. /* 路径常量 */
  8. public const string AB_RESOURCES = "AB_Res";
  9.  
  10. /// <summary>
  11. /// 获取AB资源的输入目录
  12. /// </summary>
  13. public static string GetABResourcesPath() {
  14. return Application.dataPath + "/" + AB_RESOURCES;
  15. }
  16.  
  17. /// <summary>
  18. /// 获取AB资源的输出目录
  19. /// 1. 平台路径
  20. /// 2. 平台的名称
  21. /// </summary>
  22. public static string GetABOutputPath() {
  23. return GetPlatformPath() + "/" + GetPlatformName();
  24. }
  25.  
  26. /// <summary>
  27. /// 获取平台路径
  28. /// </summary>
  29. private static string GetPlatformPath() {
  30. string platformPath = string.Empty;
  31.  
  32. switch (Application.platform) {
  33. case RuntimePlatform.WindowsPlayer:
  34. case RuntimePlatform.WindowsEditor:
  35. platformPath = Application.streamingAssetsPath;
  36. break;
  37. case RuntimePlatform.IPhonePlayer:
  38. case RuntimePlatform.Android:
  39. platformPath = Application.persistentDataPath;
  40. break;
  41. }
  42. return platformPath;
  43. }
  44.  
  45. /// <summary>
  46. /// 获取平台名称
  47. /// </summary>
  48. public static string GetPlatformName() {
  49. string platformName = string.Empty;
  50.  
  51. switch (Application.platform) {
  52. case RuntimePlatform.WindowsPlayer:
  53. case RuntimePlatform.WindowsEditor:
  54. platformName = "Windows";
  55. break;
  56. case RuntimePlatform.IPhonePlayer:
  57. platformName = "iPhone";
  58. break;
  59. case RuntimePlatform.Android:
  60. platformName = "Android";
  61. break;
  62. }
  63. return platformName;
  64. }
  65.  
  66. /// <summary>
  67. /// 获取WWW下载(AB包)路径
  68. /// </summary>
  69. public static string GetWWWPath() {
  70. string WWWPath = string.Empty;
  71.  
  72. switch (Application.platform) {
  73. case RuntimePlatform.WindowsPlayer:
  74. case RuntimePlatform.WindowsEditor:
  75. WWWPath = "file://" + GetABOutputPath();
  76. break;
  77. case RuntimePlatform.Android:
  78. WWWPath = "jar:file://" + GetABOutputPath();
  79. break;
  80. case RuntimePlatform.IPhonePlayer:
  81. WWWPath = GetABOutputPath() + "/Raw/";
  82. break;
  83. }
  84.  
  85. return WWWPath;
  86. }
  87. }

PathTools

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. /// <summary>
  8. /// 读取AssetBundle依赖关系文件
  9. /// </summary>
  10. public class ABManifestLoader : System.IDisposable {
  11.  
  12. private static ABManifestLoader instance;
  13.  
  14. private AssetBundleManifest manifest;
  15.  
  16. private string manifestPath;
  17.  
  18. // 读取Manifest的AB
  19. private AssetBundle manifestAB;
  20.  
  21. private bool isLoaded;
  22.  
  23. public bool IsLoaded {
  24. get {
  25. return isLoaded;
  26. }
  27. }
  28.  
  29. public static ABManifestLoader Instance {
  30. get {
  31. if (instance == null) {
  32. instance = new ABManifestLoader();
  33. }
  34. return instance;
  35. }
  36. }
  37.  
  38. private ABManifestLoader() {
  39. manifestPath = PathTools.GetWWWPath() + "/" + PathTools.GetPlatformName();
  40.  
  41. manifest = null;
  42. manifestAB = null;
  43. isLoaded = false;
  44. }
  45.  
  46. /// <summary>
  47. /// 加载Manifest清单文件
  48. /// </summary>
  49. /// <returns></returns>
  50. public IEnumerator LoadManifest() {
  51. using (WWW www = new WWW(manifestPath)) {
  52. yield return www;
  53.  
  54. if (www.progress >= ) {
  55. AssetBundle ab = www.assetBundle;
  56.  
  57. if (ab != null) {
  58. manifestAB = ab;
  59. manifest = manifestAB.LoadAsset(ABDefine.ASSETBUNDLEMANIFEST) as AssetBundleManifest; // "AssetBundleManifest"固定写法
  60. isLoaded = true;
  61. } else {
  62. Debug.Log(GetType() + "/LoadManifest()/WWW下载出错,请检查! manifestPath = " + manifestPath + " 错误信息: " + www.error);
  63. }
  64. }
  65. }
  66. }
  67.  
  68. /// <summary>
  69. /// 获取Manifest
  70. /// </summary>
  71. public AssetBundleManifest GetABManifest() {
  72. if (isLoaded) {
  73. if (manifest != null) {
  74. return manifest;
  75. } else {
  76. Debug.Log(GetType() + "/GetABManifest()/manifest == null!请检查");
  77. }
  78. } else {
  79. Debug.Log(GetType() + "/GetABManifest()/isLoaded == false,Manifest没有加载完毕!请检查");
  80. }
  81.  
  82. return null;
  83. }
  84.  
  85. /// <summary>
  86. /// 获取Manifest中指定包名的依赖项
  87. /// </summary>
  88. /// <returns></returns>
  89. public string[] GetAllDependency(string abName) {
  90. if (manifest != null && !string.IsNullOrEmpty(abName)) {
  91. return manifest.GetAllDependencies(abName);
  92. }
  93. return null;
  94. }
  95.  
  96. /// <summary>
  97. /// 释放资源
  98. /// </summary>
  99. public void Dispose() {
  100. if (manifestAB != null) {
  101. manifestAB.Unload(true);
  102. }
  103. }
  104. }
  105. }

ABManifestLoader

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. /// <summary>
  8. /// 1. 存储指定AB包的所有依赖关系包
  9. /// 2. 存储指定AB包的所有被引用关系包
  10. /// </summary>
  11. public class ABRelation {
  12.  
  13. // 当前AB包名
  14. private string abName;
  15. // 当前AB包的所有依赖包
  16. private List<string> dependencyABList;
  17. // 当前AB包的所有被引用包
  18. private List<string> referenceABList;
  19.  
  20. public ABRelation(string abName) {
  21. if (!string.IsNullOrEmpty(abName)) {
  22. this.abName = abName;
  23. }
  24.  
  25. dependencyABList = new List<string>();
  26. referenceABList = new List<string>();
  27.  
  28. }
  29.  
  30. /* 依赖关系 */
  31.  
  32. /// <summary>
  33. /// 增加依赖关系
  34. /// </summary>
  35. public void AddDependency(string abName) {
  36. if (!dependencyABList.Contains(abName)) {
  37. dependencyABList.Add(abName);
  38. }
  39. }
  40.  
  41. /// <summary>
  42. /// 移除依赖关系
  43. /// </summary>
  44. /// <returns>
  45. /// true 此AB没有依赖项
  46. /// false 此AB还有依赖项
  47. /// </returns>
  48. public bool RemoveDependency(string abName) {
  49. if (dependencyABList.Contains(abName)) {
  50. dependencyABList.Remove(abName);
  51. }
  52.  
  53. if (dependencyABList.Count > ) {
  54. return false;
  55. } else {
  56. return true;
  57. }
  58. }
  59.  
  60. /// <summary>
  61. /// 获取所有依赖关系
  62. /// </summary>
  63. /// <returns></returns>
  64. public List<string> GetAllDependency() {
  65. return dependencyABList;
  66. }
  67.  
  68. /* 被引用关系 */
  69.  
  70. /// <summary>
  71. /// 增加被引用关系
  72. /// </summary>
  73. public void AddReference(string abName) {
  74. if (!referenceABList.Contains(abName)) {
  75. referenceABList.Add(abName);
  76. }
  77. }
  78.  
  79. /// <summary>
  80. /// 移除被引用关系
  81. /// </summary>
  82. /// <returns>
  83. /// true 此AB没有被引用项
  84. /// false 此AB还有被引用项
  85. /// </returns>
  86. public bool RemoveReference(string abName) {
  87. if (referenceABList.Contains(abName)) {
  88. referenceABList.Remove(abName);
  89. }
  90.  
  91. if (dependencyABList.Count > ) {
  92. return false;
  93. } else {
  94. return true;
  95. }
  96. }
  97.  
  98. /// <summary>
  99. /// 获取所有被引用关系
  100. /// </summary>
  101. /// <returns></returns>
  102. public List<string> GetAllReference() {
  103. return referenceABList;
  104. }
  105. }
  106. }

ABRelation

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. /// <summary>
  8. /// 框架主流程(4): 所有场景的AssetBundle管理
  9. ///
  10. /// 1. 读取Manifest
  11. /// 2. 以场景为单位,管理整个项目中所有的AssetBundle包
  12. /// </summary>
  13. public class AssetBundleMgr : MonoBehaviour {
  14.  
  15. private static AssetBundleMgr instance;
  16.  
  17. private Dictionary<string, MultiABMgr> multiABMgrDict = new Dictionary<string, MultiABMgr>();
  18.  
  19. private AssetBundleManifest manifest = null;
  20.  
  21. public static AssetBundleMgr Instance() {
  22. if (instance == null) {
  23. instance = new GameObject("AssetBundleMgr").AddComponent<AssetBundleMgr>();
  24. }
  25. return instance;
  26. }
  27.  
  28. private AssetBundleMgr() {
  29.  
  30. }
  31.  
  32. private void Awake() {
  33. StartCoroutine(ABManifestLoader.Instance.LoadManifest());
  34. }
  35.  
  36. public IEnumerator LoadAssetBundle(string sceneName, string abName, ABLoadComplete abLoadComplete) {
  37. // 参数检查
  38. if (string.IsNullOrEmpty(sceneName) || string.IsNullOrEmpty(abName)) {
  39. Debug.LogError(GetType() + "/LoadAssetBundle()/sceneName or abName == null,请检查!");
  40. yield return null;
  41. }
  42.  
  43. // 等待Manifest文件加载完成
  44. while (!ABManifestLoader.Instance.IsLoaded) {
  45. yield return null;
  46. }
  47. manifest = ABManifestLoader.Instance.GetABManifest();
  48. if (manifest == null) {
  49. Debug.LogError(GetType() + "/LoadAssetBundle()/manifest == null,请检查!");
  50. yield return null;
  51. }
  52.  
  53. // 加入当前场景
  54. if (!multiABMgrDict.ContainsKey(sceneName)) {
  55. MultiABMgr multiABMgr = new MultiABMgr(sceneName, abName, abLoadComplete);
  56. multiABMgrDict.Add(sceneName, multiABMgr);
  57. }
  58.  
  59. // 调用下一层(多包管理)
  60. MultiABMgr tempMultiABMgr = multiABMgrDict[sceneName];
  61.  
  62. if (tempMultiABMgr == null) {
  63. Debug.LogError(GetType() + "/LoadAssetBundle()/tempMultiABMgr == null,请检查!");
  64. }
  65.  
  66. yield return tempMultiABMgr.LoadAssetBundle(abName);
  67. }
  68.  
  69. /// <summary>
  70. /// 加载(AB包中)资源
  71. /// </summary>
  72. public UnityEngine.Object LoadAsset(string sceneName, string abName, string assetName, bool isCache) {
  73. if (multiABMgrDict.ContainsKey(sceneName)) {
  74. MultiABMgr multiABMgr = multiABMgrDict[sceneName];
  75. return multiABMgr.LoadAsset(abName, assetName, isCache);
  76. }
  77.  
  78. Debug.LogError(GetType() + "/LoadAsset()/找不到场景名称,无法加载资源,请检查! sceneName: " + sceneName);
  79.  
  80. return null;
  81. }
  82.  
  83. /// <summary>
  84. /// 释放资源
  85. /// </summary>
  86. public void DisposeAllAsset(string sceneName) {
  87. if (multiABMgrDict.ContainsKey(sceneName)) {
  88. MultiABMgr multiABMgr = multiABMgrDict[sceneName];
  89. multiABMgr.DisposeAllAsset();
  90. } else {
  91. Debug.LogError(GetType() + "/LoadAsset()/找不到场景名称,无法释放资源,请检查! sceneName: " + sceneName);
  92. }
  93. }
  94.  
  95. }
  96. }

AssetBundleMgr

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. /// <summary>
  8. /// 框架主流程 1. AB资源加载类
  9. ///
  10. /// AB包内资源的加载
  11. ///
  12. /// 功能:
  13. /// 1. 管理与加载指定AB的资源
  14. /// 2. 加载具有"缓存功能"的资源,带选用参数
  15. /// 3. 卸载,释放AB资源
  16. /// 4. 查看当前AB资源
  17. /// </summary>
  18. public class AssetLoader : System.IDisposable {
  19.  
  20. private AssetBundle currentAB;
  21.  
  22. private Dictionary<string, Object> ht;
  23.  
  24. public AssetLoader(AssetBundle ab) {
  25. if (ab != null) {
  26. currentAB = ab;
  27. ht = new Dictionary<string, Object>();
  28. } else {
  29. Debug.LogError(GetType() + "/构造函数 AssetBundle()/ 参数 ab == null!,请检查");
  30. }
  31. }
  32.  
  33. /// <summary>
  34. /// 加载当前包中指定的资源
  35. /// </summary>
  36. public UnityEngine.Object LoadAsset(string assetName, bool isCache = false) {
  37. return LoadResource<UnityEngine.Object>(assetName, isCache);
  38. }
  39.  
  40. /// <summary>
  41. /// 加载当前AB包的资源
  42. /// </summary>
  43. private T LoadResource<T>(string assetName, bool isCahce) where T: UnityEngine.Object {
  44. if (ht.ContainsKey(assetName)) {
  45. return ht[assetName] as T;
  46. }
  47.  
  48. T tempRes = currentAB.LoadAsset<T>(assetName);
  49.  
  50. if (tempRes != null && isCahce) {
  51. ht.Add(assetName, tempRes);
  52. } else if (tempRes == null) {
  53. Debug.LogError(GetType() + "/LoadResource<T>/参数 tempRes==null, 请检查");
  54. }
  55.  
  56. return tempRes;
  57. }
  58.  
  59. /// <summary>
  60. /// 卸载指定资源
  61. /// </summary>
  62. public bool UnLoadAsset(UnityEngine.Object asset) {
  63. if (asset != null) {
  64. Resources.UnloadAsset(asset);
  65. return true;
  66. }
  67.  
  68. Debug.LogError(GetType() + "/UnLoadAsset()/参数 asset == null, 请检查");
  69. return false;
  70. }
  71.  
  72. /// <summary>
  73. /// 释放当前AssetBundle内存镜像资源
  74. /// </summary>
  75. public void Dispose() {
  76. currentAB.Unload(false);
  77. }
  78.  
  79. /// <summary>
  80. /// 释放当前AssetBundle内存镜像资源,且释放内存资源
  81. /// </summary>
  82. public void DisposeAll() {
  83. currentAB.Unload(true);
  84. }
  85.  
  86. /// <summary>
  87. /// 查询当前AssetBundle中包含的所有资源名称
  88. /// </summary>
  89. /// <returns></returns>
  90. public string[] GetAllAssetName() {
  91. return currentAB.GetAllAssetNames();
  92. }
  93. }
  94. }

AssetLoader

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. /// <summary>
  8. /// 主流程(3): (一个场景中)多个AssetBundle管理
  9. ///
  10. /// 1. 获取AB包的依赖与引用
  11. /// 2. 管理AB包之间的自动连锁(递归)加载机制
  12. /// </summary>
  13. public class MultiABMgr {
  14.  
  15. private SingleABLoader singleABLoader;
  16.  
  17. // 缓存AB包,防止重复加载
  18. private Dictionary<string, SingleABLoader> singleABLoaderDict;
  19.  
  20. // 当前场景(调试使用)
  21. private string currentSceneName;
  22.  
  23. private string currentABName;
  24.  
  25. private Dictionary<string, ABRelation> abRelationDict;
  26.  
  27. private ABLoadComplete loadCompleteHandler;
  28.  
  29. public MultiABMgr(string sceneName, string abName, ABLoadComplete abLoadComplete) {
  30. currentSceneName = sceneName;
  31. currentABName = abName;
  32. singleABLoaderDict = new Dictionary<string, SingleABLoader>();
  33. abRelationDict = new Dictionary<string, ABRelation>();
  34.  
  35. loadCompleteHandler = abLoadComplete;
  36. }
  37.  
  38. /// <summary>
  39. /// 完成指定AB包的调用
  40. /// </summary>
  41. /// <param name="abName"></param>
  42. private void LoadABCompleted(string abName) {
  43. //Debug.Log(GetType() + "/当前完成ABName:" + abName);
  44. if (abName.Equals(currentABName)) {
  45. if (loadCompleteHandler != null) {
  46. loadCompleteHandler(abName);
  47. }
  48. }
  49. }
  50.  
  51. /// <summary>
  52. /// 加载AB包
  53. /// </summary>
  54. public IEnumerator LoadAssetBundle(string abName) {
  55. // AB包关系的建立
  56. if (!abRelationDict.ContainsKey(abName)) {
  57. ABRelation abRelation = new ABRelation(abName);
  58. abRelationDict.Add(abName, abRelation);
  59. }
  60.  
  61. ABRelation tempABRelation = abRelationDict[abName];
  62.  
  63. // 得到指定AB包所有的依赖关系(查询manifest文件)
  64. string[] abDependencyArr = ABManifestLoader.Instance.GetAllDependency(abName);
  65.  
  66. foreach (var item in abDependencyArr) {
  67.  
  68. Debug.Log("abName: " + abName + ", depenABName: " + item);
  69.  
  70. // 添加依赖项
  71. tempABRelation.AddDependency(item);
  72. // 添加被引用项
  73. yield return LoadReference(item, abName);
  74. }
  75.  
  76. //Debug.Log(tempABRelation.GetAllDependency());
  77. //Debug.Log(tempABRelation.GetAllReference());
  78.  
  79. // 真正加载AB包
  80. if (singleABLoaderDict.ContainsKey(abName)) {
  81. yield return singleABLoaderDict[abName].LoadAssetBundle();
  82. } else {
  83. singleABLoader = new SingleABLoader(abName, LoadABCompleted);
  84. singleABLoaderDict.Add(abName, singleABLoader);
  85.  
  86. yield return singleABLoader.LoadAssetBundle();
  87. }
  88. }
  89.  
  90. /// <summary>
  91. /// 加载被引用AB包
  92. /// </summary>
  93. private IEnumerator LoadReference(string abName, string refABName) {
  94.  
  95. if (abRelationDict.ContainsKey(abName)) {
  96. ABRelation tempABRelation = abRelationDict[abName];
  97. // 添加AB包被引用关系(被依赖)
  98. tempABRelation.AddReference(refABName);
  99. } else {
  100. ABRelation tempABRelation = new ABRelation(abName);
  101. tempABRelation.AddReference(refABName);
  102. abRelationDict.Add(abName, tempABRelation);
  103.  
  104. // 开始加载依赖的包
  105. yield return LoadAssetBundle(abName);
  106. }
  107. }
  108.  
  109. /// <summary>
  110. /// 加载(AB包中)资源
  111. /// </summary>
  112. public UnityEngine.Object LoadAsset(string abName, string assetName, bool isCache) {
  113. foreach (var item in singleABLoaderDict.Keys) {
  114. if (abName == item) {
  115. return singleABLoaderDict[item].LoadAsset(assetName, isCache);
  116. }
  117. }
  118.  
  119. Debug.LogError(GetType() + "/LoadAsset()/找不到AssetBundle包,无法加载资源,请检查! abName = " + abName + ", assetName = " + assetName);
  120.  
  121. return null;
  122. }
  123.  
  124. /// <summary>
  125. /// 释放本场景中所有的资源
  126. /// </summary>
  127. public void DisposeAllAsset() {
  128. try {
  129. foreach (var item in singleABLoaderDict.Values) {
  130. item.DisposeAll();
  131. }
  132. } finally {
  133. singleABLoaderDict.Clear();
  134. singleABLoaderDict = null;
  135.  
  136. abRelationDict.Clear();
  137. abRelationDict = null;
  138.  
  139. currentABName = null;
  140. currentSceneName = null;
  141. loadCompleteHandler = null;
  142.  
  143. Resources.UnloadUnusedAssets();
  144. System.GC.Collect();
  145. }
  146. }
  147. }
  148. }

MultiABMgr

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. /// <summary>
  8. /// 框架主流程
  9. /// 2. WWW 加载AssetBundle
  10. ///
  11. /// AB包内资源的加载
  12. ///
  13. /// 功能:
  14. /// 1. 管理与加载指定AB的资源
  15. /// 2. 加载具有"缓存功能"的资源,带选用参数
  16. /// 3. 卸载,释放AB资源
  17. /// 4. 查看当前AB资源
  18. /// </summary>
  19. public class SingleABLoader : System.IDisposable {
  20.  
  21. private AssetLoader assetLoader;
  22.  
  23. private ABLoadComplete abLoadCompleteHandler;
  24.  
  25. private string abName;
  26.  
  27. private string abDownloadPath;
  28.  
  29. public SingleABLoader(string abName, ABLoadComplete loadComplete) {
  30. assetLoader = null;
  31.  
  32. abLoadCompleteHandler = loadComplete;
  33.  
  34. this.abName = abName;
  35. abDownloadPath = PathTools.GetWWWPath() + "/" + abName;
  36.  
  37. }
  38.  
  39. public IEnumerator LoadAssetBundle() {
  40. using (WWW www = new WWW(abDownloadPath)) {
  41. yield return www;
  42.  
  43. if (www.progress >= ) {
  44. AssetBundle ab = www.assetBundle;
  45.  
  46. if (ab != null) {
  47. assetLoader = new AssetLoader(ab);
  48.  
  49. if (abLoadCompleteHandler != null) {
  50. abLoadCompleteHandler(abName);
  51. }
  52.  
  53. } else {
  54. Debug.LogError(GetType() + "/LoadAssetBundle()/www下载出错,请检查! AssetBundle URL: " + abDownloadPath + " 错误信息: " + www.error);
  55. }
  56. }
  57. }
  58. }
  59.  
  60. /// <summary>
  61. /// 加载(AB包内)资源
  62. /// </summary>
  63. public UnityEngine.Object LoadAsset(string assetName, bool isCache) {
  64. if (assetLoader != null) {
  65. return assetLoader.LoadAsset(assetName, isCache);
  66. }
  67. Debug.LogError(GetType() + "/LoadAsset/assetLoader==null!, 请检查!");
  68. return null;
  69. }
  70.  
  71. /// <summary>
  72. /// 卸载(AB包内)资源
  73. /// </summary>
  74. public void UnLoadAsset(UnityEngine.Object asset) {
  75. if (assetLoader != null) {
  76. assetLoader.UnLoadAsset(asset);
  77. } else {
  78. Debug.LogError(GetType() + "/UnLoadAsset()/参数 assetLoader == null, 请检查!");
  79. }
  80. }
  81.  
  82. /// <summary>
  83. /// 释放资源
  84. /// </summary>
  85. public void Dispose() {
  86. if (assetLoader != null) {
  87. assetLoader.Dispose();
  88. assetLoader = null;
  89. } else {
  90. Debug.LogError(GetType() + "/Dispose()/参数 assetLoader == null, 请检查!");
  91. }
  92. }
  93.  
  94. /// <summary>
  95. /// 释放当前AssetBundle资源包,且卸载所有资源
  96. /// </summary>
  97. public void DisposeAll() {
  98. if (assetLoader != null) {
  99. assetLoader.DisposeAll();
  100. assetLoader = null;
  101. } else {
  102. Debug.LogError(GetType() + "/DisposeAll()/参数 assetLoader == null, 请检查!");
  103. }
  104. }
  105.  
  106. /// <summary>
  107. /// 查询当前AssetBundle包中所有的资源
  108. /// </summary>
  109. public string[] GetAllAssetName() {
  110. if (assetLoader != null) {
  111. return assetLoader.GetAllAssetName();
  112. }
  113. Debug.LogError(GetType() + "/RetrieveAllAssetName()/参数 assetLoader == null, 请检查!");
  114.  
  115. return null;
  116. }
  117. }
  118. }

SingleABLoader

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. public class Test_SingleABLoader : MonoBehaviour {
  8.  
  9. private SingleABLoader loader = null;
  10.  
  11. private string dependABName1 = "scene_1/textures.ab";
  12. private string dependABName2 = "scene_1/materials.ab";
  13. private string abName1 = "scene_1/prefabs.ab";
  14.  
  15. private string assetName1 = "TestCubePrefab.prefab";
  16.  
  17. #region 简单(无依赖包)预设的加载
  18.  
  19. //void Start() {
  20. // loader = new SingleABLoader(abName1, LoadComplete);
  21. // StartCoroutine(loader.LoadAssetBundle());
  22. //}
  23.  
  24. //private void LoadComplete(string abName) {
  25.  
  26. // var prefab = loader.LoadAsset(assetName1, false);
  27. // GameObject.Instantiate(prefab);
  28. //}
  29.  
  30. #endregion
  31.  
  32. void Start() {
  33. //SingleABLoader dependABLoader = new SingleABLoader(dependABName1, LoadDependAB1Complete);
  34. //StartCoroutine(dependABLoader.LoadAssetBundle());
  35.  
  36. //StartCoroutine(ABManifestLoader.Instance.LoadManifest());
  37. }
  38.  
  39. void Update() {
  40. if (Input.GetKeyDown(KeyCode.A)) {
  41. Debug.Log("释放资源");
  42. //loader.Dispose();
  43. loader.DisposeAll();
  44. }
  45. }
  46.  
  47. private void LoadDependAB1Complete(string abName) {
  48. Debug.Log(abName + "加载完成");
  49.  
  50. SingleABLoader dependABLoader = new SingleABLoader(dependABName2, LoadDependAB2Complete);
  51. StartCoroutine(dependABLoader.LoadAssetBundle());
  52. }
  53.  
  54. private void LoadDependAB2Complete(string abName) {
  55. Debug.Log(abName + "加载完成");
  56.  
  57. loader = new SingleABLoader(abName1, LoadAB1Complete);
  58. StartCoroutine(loader.LoadAssetBundle());
  59. }
  60.  
  61. private void LoadAB1Complete(string abName) {
  62. Debug.Log(abName + "加载完成");
  63.  
  64. var prefab = loader.LoadAsset(assetName1, false);
  65. GameObject.Instantiate(prefab);
  66.  
  67. string[] arr = loader.GetAllAssetName();
  68.  
  69. foreach (var item in arr) {
  70. Debug.Log(item);
  71. }
  72. }
  73.  
  74. }
  75. }

Test_SingleABLoader

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. namespace ABFramework {
  6.  
  7. public class Test_Framework : MonoBehaviour {
  8.  
  9. private string sceneName = "scene_1";
  10.  
  11. private string abName = "scene_1/prefabs.ab";
  12.  
  13. private string assetName = "TestCubePrefab.prefab";
  14.  
  15. private void Start() {
  16. Debug.Log("开始 ABFramework 测试");
  17.  
  18. // 调用AB包(连锁智能调用AB包)
  19. StartCoroutine(AssetBundleMgr.Instance().LoadAssetBundle(sceneName, abName, LoadALLABComplete));
  20. }
  21.  
  22. private void LoadALLABComplete(string abName) {
  23. Debug.Log("所有的AB包都已经加载完毕了");
  24.  
  25. Object tempObj = AssetBundleMgr.Instance().LoadAsset(sceneName, abName, assetName, false);
  26.  
  27. if (tempObj != null) {
  28. Instantiate(tempObj);
  29. }
  30. }
  31.  
  32. private void Update() {
  33. if (Input.GetKeyDown(KeyCode.A)) {
  34. Debug.Log("测试销毁资源");
  35. AssetBundleMgr.Instance().DisposeAllAsset(sceneName);
  36. }
  37. }
  38. }
  39. }

Test_Framework

Lua编程 (已看)

  https://www.lua.org/

  https://www.runoob.com/lua/lua-tutorial.html

  https://github.com/rjpcomputing/luaforwindows/releases

  http://luadist.org/

xLua游戏中的热更新(基于Unity2017) (已看)

  https://gameinstitute.qq.com/community/detail/111400

  https://github.com/Tencent/xLua

  1. CSharpCallLua.lua.txt
  2.  
  3. print('hi')
  4.  
  5. a =
  6. str = "siki"
  7. isDie = false
  8.  
  9. person = {
  10. name = "siki1",
  11. ,
  12. ,
  13. ,
  14. ,
  15. age = ,
  16. eat = function(self, a, b)
  17. print(a + b)
  18. end
  19. }
  20.  
  21. function add(a, b)
  22. print(a + b)
  23. return a + b, a, b
  24. end
  25.  
  26. --[[
  27.  
  28. function person:eat(a,b)
  29. print(a + b)
  30. end
  31.  
  32. --]]
  33.  
  34. CSharpCallLua.cs
  35.  
  36. using System.Collections;
  37. using System.Collections.Generic;
  38. using UnityEngine;
  39. using XLua;
  40. using System;
  41.  
  42. public class CSharpCallLua : MonoBehaviour {
  43.  
  44. void Start() {
  45. LuaEnv luaEnv = new LuaEnv();
  46. luaEnv.DoString("require 'CSharpCallLua'");
  47.  
  48. int a = luaEnv.Global.Get<int>("a");
  49. print(a);
  50.  
  51. string str = luaEnv.Global.Get<string>("str");
  52. print(str);
  53.  
  54. bool isDie = luaEnv.Global.Get<bool>("isDie");
  55. print(isDie);
  56.  
  57. //Person p = luaEnv.Global.Get<Person>("person");
  58. //print(p.name + "-" + p.age);
  59.  
  60. //IPerson p = luaEnv.Global.Get<IPerson>("person");
  61. //print(p.name + "-" + p.age);
  62. //p.name = "Sikiedu.com";
  63. //p.eat(12, 34);
  64. //luaEnv.DoString("print(person.name)");
  65. //luaEnv.Dispose();
  66.  
  67. //Dictionary<string,object> dict = luaEnv.Global.Get<Dictionary<string, object>>("person");
  68.  
  69. //foreach (string key in dict.Keys) {
  70. // print(key + "-" + dict[key]);
  71. //}
  72.  
  73. //List<object> list = luaEnv.Global.Get<List<object>>("person");
  74.  
  75. //foreach (object o in list) {
  76. // print(o);
  77. //}
  78.  
  79. //LuaTable tab = luaEnv.Global.Get<LuaTable>("person");
  80. //print(tab.Get<string>("name"));
  81. //print(tab.Length);
  82.  
  83. //Action<int, int> act = luaEnv.Global.Get<Action<int, int>>("add");
  84. //act(1, 2);
  85.  
  86. //Add add = luaEnv.Global.Get<Add>("add");
  87. //int resa, resb;
  88. //int res = add(1, 2, out resa, out resb);
  89. //print(res + " " + resa + " " + resb);
  90.  
  91. LuaFunction func = luaEnv.Global.Get<LuaFunction>("add");
  92. object[] os = func.Call(, );
  93. foreach (object o in os) {
  94. print(o);
  95. }
  96.  
  97. luaEnv.Dispose();
  98. }
  99.  
  100. [CSharpCallLua]
  101. delegate int Add(int a, int b, out int resa, out int resb);
  102.  
  103. class Person {
  104. public string name;
  105. public int age;
  106. }
  107.  
  108. [CSharpCallLua]
  109. interface IPerson {
  110. string name { get; set; }
  111. int age { get; set; }
  112. void eat(int a, int b);
  113. }
  114. }
  115.  
  116. LuaCallCSharp.lua.txt
  117.  
  118. CS.UnityEngine.GameObject("new by lua")
  119.  
  120. print(CS.UnityEngine.Time.deltaTime)
  121.  
  122. local camera = CS.UnityEngine.GameObject.Find("Main Camera")
  123. camera.name = "update"
  124.  
  125. local cameraCom = camera:GetComponent("Camera")
  126. CS.UnityEngine.GameObject.Destroy(cameraCom)
  127.  
  128. LuaCallCSharp.cs
  129.  
  130. using System.Collections;
  131. using System.Collections.Generic;
  132. using UnityEngine;
  133. using XLua;
  134.  
  135. public class LuaCallCSharp : MonoBehaviour {
  136.  
  137. // Use this for initialization
  138. void Start () {
  139. LuaEnv luaEnv = new LuaEnv();
  140.  
  141. luaEnv.DoString("require 'LuaCallCSharp'");
  142.  
  143. luaEnv.Dispose();
  144. }
  145.  
  146. // Update is called once per frame
  147. void Update () {
  148.  
  149. }
  150. }

游戏热更新实战案例(基于xLua) (已看)

1.0版本

Effect

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. /// <summary>
  7. /// 星星闪耀的特效
  8. /// </summary>
  9. public class Shine : MonoBehaviour {
  10.  
  11. private Image img;
  12. public float speed=;
  13. private bool add;
  14.  
  15. public void Awake()
  16. {
  17. img = GetComponent<Image>();
  18. }
  19. // Use this for initialization
  20. void Start () {
  21.  
  22. }
  23.  
  24. // Update is called once per frame
  25. void Update () {
  26. transform.Rotate(Vector3.forward * , Space.World);
  27. if (!add)
  28. {
  29. img.color -= new Color(, , , Time.deltaTime * speed);
  30. if (img.color.a <=0.2f)
  31. {
  32. add = true;
  33. }
  34. }
  35. else
  36. {
  37. img.color += new Color(, , , Time.deltaTime * speed);
  38. if (img.color.a >=0.8f)
  39. {
  40. add = false;
  41. }
  42. }
  43.  
  44. }
  45. }

Shine  Main/Canvas/Panel/UI_Stars/Img_Star

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. /// <summary>
  7. /// 隐藏显示闪耀UI的特效,比如枪,星星
  8. /// </summary>
  9. public class ShineHide : MonoBehaviour {
  10. private float timeVal = ;
  11. private bool isAdd = false;
  12. private Image img;
  13. public float defineTime = ;
  14. void Awake()
  15. {
  16. img = GetComponent<Image>();
  17.  
  18. }
  19.  
  20. // Use this for initialization
  21. void Start () {
  22.  
  23. }
  24.  
  25. // Update is called once per frame
  26. void Update () {
  27. timeVal += Time.deltaTime;
  28. if (!isAdd)
  29. {
  30. img.color -= new Color(, , , Time.deltaTime * );
  31. if (timeVal > defineTime)
  32. {
  33. img.color = new Color(img.color.r, img.color.g, img.color.b, );
  34. isAdd = true;
  35. timeVal = ;
  36. }
  37. }
  38. else
  39. {
  40. img.color += new Color(, , , Time.deltaTime * );
  41. if (timeVal > defineTime)
  42. {
  43. img.color = new Color(img.color.r, img.color.g, img.color.b, );
  44. isAdd = false;
  45. timeVal = ;
  46. }
  47.  
  48. }
  49. }
  50.  
  51. }

ShineHide  Main/Canvas/Panel/UI_StartGame/But_StartGame

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 爆炸特效
  6. /// </summary>
  7. public class Explosion : MonoBehaviour {
  8.  
  9. public float DestoryTime = 0.2f;
  10.  
  11. // Use this for initialization
  12. void Start () {
  13. Destroy(this.gameObject, DestoryTime);
  14. }
  15.  
  16. // Update is called once per frame
  17. void Update () {
  18. transform.localScale +=new Vector3(Time.deltaTime*, Time.deltaTime*, Time.deltaTime*) ;
  19. }
  20. }

Explosion  Prefabs/Effects/explosion...

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Pao : MonoBehaviour {
  5. /// <summary>
  6. /// 游戏中产生的泡泡
  7. /// </summary>
  8. public int moveSpeed;
  9. public bool isGamePao;
  10.  
  11. // Use this for initialization
  12. void Start () {
  13.  
  14. if (isGamePao)
  15. {
  16. moveSpeed = Random.Range(, );
  17. Destroy(this.gameObject, Random.Range(0.5f, 1f));
  18. }
  19. else
  20. {
  21. moveSpeed = Random.Range(, );
  22. Destroy(this.gameObject, Random.Range(7f, 10f));
  23. }
  24. }
  25.  
  26. // Update is called once per frame
  27. void Update () {
  28. transform.Translate(-transform.right*moveSpeed*Time.deltaTime,Space.World);
  29. }
  30. }

Pao  Prefabs/Effects/Pao

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /// <summary>
  6. /// boss攻击玩家产生的震动方法
  7. /// </summary>
  8. public class Shake : MonoBehaviour {
  9.  
  10. private float cameraShake = ;
  11. public GameObject UI;
  12.  
  13. // Use this for initialization
  14. void Start () {
  15.  
  16. }
  17.  
  18. // Update is called once per frame
  19. void Update () {
  20. if (Gun.Instance.bossAttack)
  21. {
  22.  
  23. UI.SetActive(true);
  24. transform.position = new Vector3((Random.Range(0f, cameraShake)) - cameraShake*0.5f, transform.position.y, transform.position.z);
  25. transform.position = new Vector3(transform.position.x, transform.position.y, (Random.Range(0f, cameraShake)) - cameraShake * 0.5f);
  26. cameraShake = cameraShake / 1.05f;
  27. if (cameraShake<0.05f)
  28. {
  29.  
  30. cameraShake= ;
  31. UI.SetActive(false);
  32. Gun.Instance.bossAttack = false;
  33. }
  34. }
  35. else
  36. {
  37. cameraShake = ;
  38. }
  39. }
  40. }

Shake  Fish/Main Camera

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. /// <summary>
  7. /// 隐藏显示闪耀UI的特效,比如枪,星星
  8. /// </summary>
  9. public class ShineHide : MonoBehaviour {
  10. private float timeVal = ;
  11. private bool isAdd = false;
  12. private Image img;
  13. public float defineTime = ;
  14. void Awake()
  15. {
  16. img = GetComponent<Image>();
  17.  
  18. }
  19.  
  20. // Use this for initialization
  21. void Start () {
  22.  
  23. }
  24.  
  25. // Update is called once per frame
  26. void Update () {
  27. timeVal += Time.deltaTime;
  28. if (!isAdd)
  29. {
  30. img.color -= new Color(, , , Time.deltaTime * );
  31. if (timeVal > defineTime)
  32. {
  33. img.color = new Color(img.color.r, img.color.g, img.color.b, );
  34. isAdd = true;
  35. timeVal = ;
  36. }
  37. }
  38. else
  39. {
  40. img.color += new Color(, , , Time.deltaTime * );
  41. if (timeVal > defineTime)
  42. {
  43. img.color = new Color(img.color.r, img.color.g, img.color.b, );
  44. isAdd = false;
  45. timeVal = ;
  46. }
  47.  
  48. }
  49. }
  50.  
  51. }

ShineHide  Fish/Canvas/Img_Gun/Img_GunLight

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /// <summary>
  6. /// 水纹播放的特效
  7. /// </summary>
  8. public class Water : MonoBehaviour {
  9.  
  10. private SpriteRenderer sr;
  11.  
  12. public Sprite[] pictures;
  13.  
  14. private int count=;
  15.  
  16. // Use this for initialization
  17. void Start () {
  18. sr = GetComponent<SpriteRenderer>();
  19. }
  20.  
  21. // Update is called once per frame
  22. void Update () {
  23. sr.sprite = pictures[count];
  24. count++;
  25. if (count==pictures.Length)
  26. {
  27. count = ;
  28. }
  29. }
  30. }

Water  Prefabs/Enemy/Fish1/Fire

Enemy

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /// <summary>
  6. /// 挡子弹的气泡
  7. /// </summary>
  8. public class Qipao : MonoBehaviour {
  9.  
  10. //属性
  11. public float moveSpeed = ;
  12.  
  13. //计时器
  14. private float rotateTime;
  15.  
  16. // Use this for initialization
  17. void Start()
  18. {
  19. Destroy(this.gameObject, );
  20. }
  21.  
  22. // Update is called once per frame
  23. void Update()
  24. {
  25.  
  26. fishMove();
  27. }
  28.  
  29. public void fishMove()
  30. {
  31. transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
  32. if (rotateTime >= )
  33. {
  34. transform.Rotate(transform.forward * Random.Range(, ), Space.World);
  35. rotateTime = ;
  36. }
  37. else
  38. {
  39. rotateTime += Time.deltaTime;
  40. }
  41. }
  42.  
  43. public void TakeDamage(int attackValue)
  44. {
  45. Destroy(this.gameObject);
  46. }
  47. }

Qipao  Prefabs/Enemy/Qipao

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// boss脚本
  6. /// </summary>
  7.  
  8. public class Boss : MonoBehaviour
  9. {
  10.  
  11. public int hp = ;
  12.  
  13. public GameObject deadEeffect;
  14. public int GetGold = ;
  15. public int GetDiamands = ;
  16. public GameObject diamands;
  17. public GameObject gold;
  18. public float moveSpeed = ;
  19. protected int m_reduceGold;
  20. protected int m_reduceDiamond;
  21.  
  22. protected Transform playerTransform;
  23.  
  24. protected GameObject fire;
  25. protected GameObject ice;
  26. protected Animator iceAni;
  27. protected Animator gameObjectAni;
  28. protected AudioSource bossAudio;
  29.  
  30. //计时器
  31. private float rotateTime;
  32. private float timeVal;
  33.  
  34. protected bool hasIce;
  35. protected bool isAttack;
  36.  
  37. void Start()
  38. {
  39. fire = transform.Find("Fire").gameObject;
  40. ice = transform.Find("Ice").gameObject;
  41. iceAni = ice.transform.GetComponent<Animator>();
  42. gameObjectAni = GetComponent<Animator>();
  43. bossAudio = GetComponent<AudioSource>();
  44. playerTransform = Gun.Instance.transform;
  45. m_reduceGold = ;
  46. m_reduceDiamond = ;
  47. }
  48.  
  49. // Update is called once per frame
  50. void Update()
  51. {
  52. //冰冻效果
  53. if (Gun.Instance.Ice)
  54. {
  55. gameObjectAni.enabled = false;
  56. ice.SetActive(true);
  57. if (!hasIce)
  58. {
  59. iceAni.SetTrigger("Ice");
  60. hasIce = true;
  61. }
  62.  
  63. }
  64. else
  65. {
  66. gameObjectAni.enabled = true;
  67. hasIce = false;
  68. ice.SetActive(false);
  69. }
  70. //灼烧效果
  71. if (Gun.Instance.Fire)
  72. {
  73. fire.SetActive(true);
  74.  
  75. }
  76. else
  77. {
  78. fire.SetActive(false);
  79. }
  80. if (Gun.Instance.Ice)
  81. {
  82. return;
  83. }
  84. //boss的行为方法
  85. Attack(m_reduceGold, m_reduceDiamond);
  86. if (!isAttack)
  87. {
  88. fishMove();
  89. }
  90.  
  91. }
  92.  
  93. public virtual void TakeDamage(int attackValue)
  94. {
  95. if (Gun.Instance.Fire)
  96. {
  97. attackValue *= ;
  98. }
  99.  
  100. hp -= attackValue;
  101. if (hp <= )
  102. {
  103. Instantiate(deadEeffect, transform.position, transform.rotation);
  104. Gun.Instance.GoldChange(GetGold * );
  105. Gun.Instance.DiamandsChange(GetDiamands * );
  106.  
  107. for (int i = ; i < ; i++)
  108. {
  109. GameObject itemGo = Instantiate(gold, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(, + * (i - ), )));
  110. itemGo.GetComponent<Gold>().bossPrize = true;
  111. }
  112. for (int i = ; i < ; i++)
  113. {
  114. GameObject itemGo = Instantiate(diamands, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(, + * (i - ), )));
  115. itemGo.GetComponent<Gold>().bossPrize = true;
  116. }
  117. Destroy(this.gameObject);
  118. }
  119. }
  120. public void fishMove()
  121. {
  122. transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
  123. if (rotateTime >= )
  124. {
  125. transform.Rotate(transform.forward * Random.Range(, ), Space.World);
  126. rotateTime = ;
  127. }
  128. else
  129. {
  130. rotateTime += Time.deltaTime;
  131. }
  132. }
  133.  
  134. public void Attack(int reduceGold, int reduceDiamond)
  135. {
  136. if (timeVal > )
  137. {
  138. transform.LookAt(playerTransform);
  139. transform.eulerAngles += new Vector3(, -, );
  140.  
  141. isAttack = true;
  142. timeVal = ;
  143. }
  144. else
  145. {
  146. timeVal += Time.deltaTime;
  147. }
  148. if (isAttack)
  149. {
  150.  
  151. gameObjectAni.SetBool("isAttack", true);
  152. transform.position = Vector3.Lerp(transform.position, playerTransform.position, / Vector3.Distance(transform.position, playerTransform.position) * Time.deltaTime * moveSpeed);
  153. if (Vector3.Distance(transform.position, playerTransform.position) <= )
  154. {
  155. if (reduceGold != )
  156. {
  157. Gun.Instance.GoldChange(reduceGold);
  158. }
  159. if (reduceDiamond != )
  160. {
  161. Gun.Instance.DiamandsChange(reduceDiamond);
  162. }
  163.  
  164. gameObjectAni.SetBool("isAttack", false);
  165. isAttack = false;
  166. Gun.Instance.BossAttack();
  167. rotateTime = ;
  168. Invoke("ReturnAngle", );
  169. }
  170. }
  171. }
  172.  
  173. public void ReturnAngle()
  174. {
  175. transform.eulerAngles = new Vector3(, , );
  176. }
  177. }

Boss  Prefabs/Enemy/Boss2

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /// <summary>
  6. /// 产鱼器
  7. /// </summary>
  8.  
  9. public class CreateFish : MonoBehaviour
  10. {
  11.  
  12. //引用
  13. public GameObject[] fishList;
  14. public GameObject[] item;
  15. public GameObject boss;
  16. public GameObject boss2;
  17. public GameObject boss3;
  18. public Transform[] CreateFishPlace;
  19.  
  20. private float ItemtimeVal = ;//游戏物体计时器
  21. private float createManyFish;
  22. private float timeVals = ;
  23.  
  24. //成员变量
  25. private int num;
  26. private int ItemNum;
  27. private int placeNum;
  28. private int CreateMorden;
  29.  
  30. //x:-26 - 26
  31. //z:-16 - 16
  32. private void Awake()
  33. {
  34.  
  35. }
  36. // Use this for initialization
  37. void Start()
  38. {
  39.  
  40. }
  41.  
  42. void Update()
  43. {
  44.  
  45. //鱼群的生成
  46. CreateALotOfFish();
  47.  
  48. //单种鱼的生成
  49. if (ItemtimeVal >= 0.5)
  50. {
  51. //位置随机数
  52. num = Random.Range(, );
  53. //游戏物体随机数
  54. ItemNum = Random.Range(, );
  55.  
  56. //产生气泡
  57. if (ItemNum < )
  58. {
  59. CreateGameObject(item[]);
  60. CreateGameObject(fishList[]);
  61. }
  62. //贝壳10% 85-94
  63. //第一种鱼42% 42
  64. if (ItemNum <= )
  65. {
  66. CreateGameObject(fishList[]);
  67. CreateGameObject(item[]);
  68. CreateGameObject(fishList[]);
  69. CreateGameObject(item[]);
  70. }
  71. //第二种鱼30% 43-72
  72. else if (ItemNum >= && ItemNum < )
  73. {
  74. CreateGameObject(fishList[]);
  75. CreateGameObject(item[]);
  76. CreateGameObject(fishList[]);
  77. }
  78. //第三种鱼10% 73-84
  79. else if (ItemNum >= && ItemNum < )
  80. {
  81. CreateGameObject(fishList[]);
  82. CreateGameObject(fishList[]);
  83. }
  84.  
  85. //第一种美人鱼5%,第二种3% 95-98 99-100
  86.  
  87. else if (ItemNum >= && ItemNum <= )
  88. {
  89. CreateGameObject(item[]);
  90. }
  91.  
  92. else if (ItemNum >= && ItemNum < )
  93. {
  94.  
  95. CreateGameObject(boss2);
  96. }
  97.  
  98. else if (ItemNum > && ItemNum < )
  99. {
  100. CreateGameObject(item[]);
  101. CreateGameObject(boss);
  102. }
  103.  
  104. else
  105. {
  106. CreateGameObject(item[]);
  107. CreateGameObject(boss3);
  108. }
  109. ItemtimeVal = ;
  110. }
  111. else
  112. {
  113. ItemtimeVal += Time.deltaTime;
  114. }
  115.  
  116. }
  117.  
  118. //生成鱼群
  119. private void CreateALotOfFish()
  120. {
  121. if (createManyFish >= )
  122. {
  123.  
  124. if (CreateMorden == )
  125. {
  126. GameObject go = fishList[Random.Range(, fishList.Length)];
  127. for (int i = ; i < ; i++)
  128. {
  129. GameObject itemGo = Instantiate(go, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(, * i, )));
  130. itemGo.GetComponent<Fish>().cantRotate = true;
  131. }
  132. createManyFish = ;
  133. }
  134. else if (CreateMorden == || CreateMorden == )
  135. {
  136. createManyFish += Time.deltaTime;
  137. if (createManyFish >= )
  138. {
  139. createManyFish = ;
  140. }
  141. if (timeVals >= 0.2f)
  142. {
  143. int num = Random.Range(, );
  144. GameObject itemGo = Instantiate(fishList[num], CreateFishPlace[placeNum].position + new Vector3(, , Random.Range(-, )), CreateFishPlace[placeNum].rotation);
  145. itemGo.GetComponent<Fish>().cantRotate = true;
  146. timeVals = ;
  147. }
  148. else
  149. {
  150. timeVals += Time.deltaTime;
  151. }
  152. }
  153.  
  154. }
  155. else
  156. {
  157. createManyFish += Time.deltaTime;
  158. placeNum = Random.Range(, );
  159. CreateMorden = Random.Range(, );
  160. }
  161. }
  162.  
  163. private void CreateFishs(GameObject go)
  164. {
  165. Instantiate(go, RandomPos(num), Quaternion.Euler(go.transform.eulerAngles));
  166. }
  167.  
  168. //产生游戏物体
  169. private void CreateGameObject(GameObject go)
  170. {
  171. Instantiate(go, RandomPos(num), Quaternion.Euler(RandomAngle(num) + go.transform.eulerAngles));
  172. }
  173. //随机位置
  174. private Vector3 RandomPos(int num)
  175. {
  176. Vector3 Vpositon = new Vector3();
  177.  
  178. switch (num)
  179. {
  180. case :
  181. Vpositon = new Vector3(-, , Random.Range(-14f, 14f));//-30 - 30
  182. break;
  183. case :
  184. Vpositon = new Vector3(Random.Range(-24f, 24f), , );//60 - 120
  185. break;
  186. case :
  187. Vpositon = new Vector3(, , Random.Range(-14f, 14f));//150-210
  188. break;
  189. case :
  190. Vpositon = new Vector3(Random.Range(-24f, 24f), , -);//-60- -120
  191. break;
  192. default:
  193. break;
  194. }
  195. return Vpositon;
  196. }
  197. //随机角度
  198. private Vector3 RandomAngle(int num)
  199. {
  200. Vector3 Vangle = new Vector3();
  201. switch (num)
  202. {
  203. case :
  204. Vangle = new Vector3(, Random.Range(-30f, 30f), );//-30 - 30
  205. break;
  206. case :
  207. Vangle = new Vector3(, Random.Range(60f, 120f), );//60 - 120
  208. break;
  209. case :
  210. Vangle = new Vector3(, Random.Range(150f, 210f), );//150-210
  211. break;
  212. case :
  213. Vangle = new Vector3(, Random.Range(-60f, -120f), );//-60- -120
  214. break;
  215. default:
  216. break;
  217. }
  218. return Vangle;
  219. }
  220.  
  221. }

CreateFish  Fish/CreateFish/Place/FishCreate

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 有护盾的boss
  6. /// </summary>
  7. public class DeffendBoss : Boss
  8. {
  9.  
  10. private bool isDeffend = false;
  11.  
  12. private float deffendTime = ;
  13.  
  14. public GameObject deffend;
  15.  
  16. void Start()
  17. {
  18. fire = transform.Find("Fire").gameObject;
  19. ice = transform.Find("Ice").gameObject;
  20. iceAni = ice.transform.GetComponent<Animator>();
  21. gameObjectAni = GetComponent<Animator>();
  22. bossAudio = GetComponent<AudioSource>();
  23. playerTransform = Gun.Instance.transform;
  24. }
  25.  
  26. // Update is called once per frame
  27. void Update()
  28. {
  29. //冰冻效果
  30. if (Gun.Instance.Ice)
  31. {
  32. gameObjectAni.enabled = false;
  33. ice.SetActive(true);
  34. if (!hasIce)
  35. {
  36. iceAni.SetTrigger("Ice");
  37. hasIce = true;
  38. }
  39.  
  40. }
  41. else
  42. {
  43. gameObjectAni.enabled = true;
  44. hasIce = false;
  45. ice.SetActive(false);
  46. }
  47. //灼烧效果
  48. if (Gun.Instance.Fire)
  49. {
  50. fire.SetActive(true);
  51.  
  52. }
  53. else
  54. {
  55. fire.SetActive(false);
  56. }
  57. if (Gun.Instance.Ice)
  58. {
  59. return;
  60. }
  61. //boss的行为方法
  62. Attack(m_reduceGold, m_reduceDiamond);
  63. if (!isAttack)
  64. {
  65. fishMove();
  66. }
  67. //保护方法
  68. if (deffendTime >= )
  69. {
  70. deffendTime = ;
  71. DeffenMe();
  72. }
  73. else
  74. {
  75. deffendTime += Time.deltaTime;
  76. }
  77. }
  78.  
  79. void DeffenMe()
  80. {
  81. isDeffend = true;
  82. deffend.SetActive(true);
  83. Invoke("CloseDeffendMe", );
  84. }
  85.  
  86. private void CloseDeffendMe()
  87. {
  88. deffend.SetActive(false);
  89. isDeffend = false;
  90. }
  91.  
  92. public override void TakeDamage(int attackValue)
  93. {
  94. if (isDeffend)
  95. {
  96. return;
  97. }
  98. base.TakeDamage(attackValue);
  99. }
  100.  
  101. }

DeffendBoss  Prefabs/Enemy/Boss1

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 普通鱼的类
  6. /// </summary>
  7.  
  8. public class Fish : MonoBehaviour
  9. {
  10.  
  11. //属性
  12. public float moveSpeed = ;
  13. public int GetCold = ;
  14. public int GetDiamands = ;
  15. public int hp = ;
  16.  
  17. //计时器
  18. private float rotateTime;
  19. private float timeVal;
  20.  
  21. //引用
  22. public GameObject gold;
  23. public GameObject diamands;
  24. private GameObject fire;
  25. private GameObject ice;
  26. private Animator iceAni;
  27. private Animator gameObjectAni;
  28. private SpriteRenderer sr;
  29. public GameObject pao;
  30.  
  31. //开关
  32. private bool hasIce = false;
  33. public bool isnet;
  34. private bool isDead = false;
  35. public bool cantRotate = false;
  36.  
  37. // Use this for initialization
  38. void Start()
  39. {
  40. fire = transform.Find("Fire").gameObject;
  41. ice = transform.Find("Ice").gameObject;
  42. iceAni = ice.transform.GetComponent<Animator>();
  43. gameObjectAni = GetComponent<Animator>();
  44. sr = GetComponent<SpriteRenderer>();
  45. Destroy(this.gameObject, );
  46.  
  47. }
  48.  
  49. // Update is called once per frame
  50. void Update()
  51. {
  52. if (timeVal >= || isDead)
  53. {
  54. sr.color -= new Color(, , , Time.deltaTime);
  55. }
  56. else
  57. {
  58. timeVal += Time.deltaTime;
  59. }
  60.  
  61. if (isDead)
  62. {
  63. return;
  64. }
  65. //冰冻效果
  66. if (Gun.Instance.Ice)
  67. {
  68. gameObjectAni.enabled = false;
  69. ice.SetActive(true);
  70. if (!hasIce)
  71. {
  72. iceAni.SetTrigger("Ice");
  73. hasIce = true;
  74. }
  75.  
  76. }
  77. else
  78. {
  79. gameObjectAni.enabled = true;
  80. hasIce = false;
  81. ice.SetActive(false);
  82. }
  83.  
  84. //灼烧方法
  85. if (Gun.Instance.Fire)
  86. {
  87. fire.SetActive(true);
  88.  
  89. }
  90. else
  91. {
  92. fire.SetActive(false);
  93. }
  94.  
  95. if (Gun.Instance.Ice)
  96. {
  97. return;
  98. }
  99. if (isnet)
  100. {
  101. Invoke("Net", 0.5f);
  102. return;
  103. }
  104. fishMove();
  105. }
  106. public void Net()
  107. {
  108. if (isnet)
  109. {
  110. isnet = false;
  111. }
  112.  
  113. }
  114.  
  115. public void fishMove()
  116. {
  117. transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
  118. if (cantRotate)
  119. {
  120. return;
  121. }
  122. if (rotateTime >= )
  123. {
  124. transform.Rotate(transform.forward * Random.Range(, ), Space.World);
  125. rotateTime = ;
  126. }
  127. else
  128. {
  129. rotateTime += Time.deltaTime;
  130. }
  131. }
  132. public void TakeDamage(int attackValue)
  133. {
  134. if (Gun.Instance.Fire)
  135. {
  136. attackValue *= ;
  137. }
  138. hp -= attackValue;
  139. if (hp <= )
  140. {
  141. isDead = true;
  142. for (int i = ; i < ; i++)
  143. {
  144. Instantiate(pao, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(, * i, )));
  145. }
  146.  
  147. gameObjectAni.SetTrigger("Die");
  148. Invoke("Prize", 0.7f);
  149. }
  150. }
  151. private void Prize()
  152. {
  153. Gun.Instance.GoldChange(GetCold);
  154. if (GetDiamands != )
  155. {
  156. Gun.Instance.DiamandsChange(GetDiamands);
  157. Instantiate(diamands, transform.position, transform.rotation);
  158. }
  159.  
  160. Instantiate(gold, transform.position, transform.rotation);
  161.  
  162. Destroy(this.gameObject);
  163. }
  164. }

Fish  Prefabs/Enemy/Fish

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 会隐藏的boss
  6. /// </summary>
  7. public class InvisibleBoss : Boss
  8. {
  9.  
  10. private bool isInvisible = false;
  11.  
  12. private float invisibleTime = ;
  13. private float recoverTime = ;
  14.  
  15. private BoxCollider box;
  16. private SpriteRenderer sr;
  17.  
  18. void Start()
  19. {
  20. fire = transform.Find("Fire").gameObject;
  21. ice = transform.Find("Ice").gameObject;
  22. iceAni = ice.transform.GetComponent<Animator>();
  23. gameObjectAni = GetComponent<Animator>();
  24. box = GetComponent<BoxCollider>();
  25. sr = GetComponent<SpriteRenderer>();
  26. bossAudio = GetComponent<AudioSource>();
  27. playerTransform = Gun.Instance.transform;
  28. }
  29.  
  30. // Update is called once per frame
  31. void Update()
  32. {
  33. //冰冻效果
  34. if (Gun.Instance.Ice)
  35. {
  36. gameObjectAni.enabled = false;
  37. ice.SetActive(true);
  38. if (!hasIce)
  39. {
  40. iceAni.SetTrigger("Ice");
  41. hasIce = true;
  42. }
  43.  
  44. }
  45. else
  46. {
  47. gameObjectAni.enabled = true;
  48. hasIce = false;
  49. ice.SetActive(false);
  50. }
  51. //灼烧效果
  52. if (Gun.Instance.Fire)
  53. {
  54. fire.SetActive(true);
  55.  
  56. }
  57. else
  58. {
  59. fire.SetActive(false);
  60. }
  61. if (Gun.Instance.Ice)
  62. {
  63. return;
  64. }
  65. //boss的行为方法
  66. Attack(m_reduceGold, m_reduceDiamond);
  67. if (!isAttack)
  68. {
  69. fishMove();
  70. }
  71. //隐形方法
  72. if (invisibleTime >= )
  73. {
  74. invisibleTime = ;
  75. Invisible();
  76. }
  77. else
  78. {
  79. invisibleTime += Time.deltaTime;
  80. }
  81. if (isInvisible)
  82. {
  83. sr.color -= new Color(, , , Time.deltaTime);
  84. box.enabled = false;
  85. }
  86. else
  87. {
  88. sr.color += new Color(, , , Time.deltaTime);
  89. if (recoverTime >= )
  90. {
  91. recoverTime = ;
  92. sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, );
  93. }
  94. else
  95. {
  96. recoverTime += Time.deltaTime;
  97. }
  98. box.enabled = true;
  99. }
  100. }
  101.  
  102. private void Invisible()
  103. {
  104. isInvisible = true;
  105. Invoke("CloseInvisible", );
  106. }
  107.  
  108. private void CloseInvisible()
  109. {
  110. isInvisible = false;
  111. }
  112. }

InvisibleBoss  Prefabs/Enemy/Boss3

Item

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /// <summary>
  6. /// 铺到贝壳的道具卡
  7. /// </summary>
  8. public class Card : MonoBehaviour {
  9.  
  10. private Transform playerTransform;
  11.  
  12. public int num;
  13.  
  14. public Sprite[] cards;
  15.  
  16. private SpriteRenderer sr;
  17.  
  18. private AudioSource audios;
  19.  
  20. // Use this for initialization
  21. void Start () {
  22. Destroy(this.gameObject,);
  23. audios = GetComponent<AudioSource>();
  24. sr = GetComponent<SpriteRenderer>();
  25. sr.sprite = cards[num];
  26. audios.Play();
  27.  
  28. }
  29.  
  30. // Update is called once per frame
  31. void Update () {
  32.  
  33. }
  34. }

Card  Prefabs/Item/Card

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 渔网
  6. /// </summary>
  7. public class FishNet : MonoBehaviour {
  8.  
  9. // Use this for initialization
  10. void Start () {
  11. Destroy(this.gameObject,0.2f);
  12. }
  13.  
  14. // Update is called once per frame
  15. void Update () {
  16. //transform.Translate(-Vector3.up * moveSpeed * Time.deltaTime,Space.World);
  17. }
  18.  
  19. private void OnTriggerEnter(Collider other)
  20. {
  21. if (other.tag=="fish")
  22. {
  23. other.GetComponent<Fish>().isnet = true;
  24.  
  25. }
  26.  
  27. }
  28. }

FishNet  Prefabs/Item/Net

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /// <summary>
  6. /// 金币,钻石
  7. /// </summary>
  8. public class Gold : MonoBehaviour
  9. {
  10.  
  11. public enum ThePlaceTo
  12. {
  13. gold,
  14. diamands,
  15. imageGold,
  16. imageDiamands
  17. }
  18. public ThePlaceTo thePlaceTo;
  19. private Transform playerTransform;
  20. public float moveSpeed = ;
  21. public GameObject star2;
  22.  
  23. private AudioSource audios;
  24. public AudioClip goldAudio;
  25. public AudioClip diamandsAudio;
  26.  
  27. private float timeVal2;
  28. public float defineTime2;
  29. private float timeBecome;
  30. private float timeVal3;
  31.  
  32. public bool bossPrize = false;
  33. private bool beginMove = false;
  34. // Use this for initialization
  35. private void Awake()
  36. {
  37. audios = GetComponent<AudioSource>();
  38. switch (thePlaceTo)
  39. {
  40. case ThePlaceTo.gold:
  41. playerTransform = Gun.Instance.goldPlace;
  42. audios.clip = goldAudio;
  43. break;
  44. case ThePlaceTo.diamands:
  45. playerTransform = Gun.Instance.diamondsPlace;
  46. audios.clip = diamandsAudio;
  47. break;
  48. case ThePlaceTo.imageGold:
  49. playerTransform = Gun.Instance.imageGoldPlace;
  50. audios.clip = goldAudio;
  51. break;
  52. case ThePlaceTo.imageDiamands:
  53. playerTransform = Gun.Instance.imageDiamandsPlace;
  54. audios.clip = diamandsAudio;
  55. break;
  56. default:
  57. break;
  58. }
  59. audios.Play();
  60.  
  61. }
  62.  
  63. void Start()
  64. {
  65.  
  66. }
  67.  
  68. // Update is called once per frame
  69. void Update()
  70. {
  71.  
  72. if (timeBecome >= 0.5f)
  73. {
  74. beginMove = true;
  75. }
  76. else
  77. {
  78. timeBecome += Time.deltaTime;
  79. }
  80. if (beginMove)
  81. {
  82. transform.position = Vector3.Lerp(transform.position, playerTransform.position, / Vector3.Distance(transform.position, playerTransform.position) * Time.deltaTime * moveSpeed);
  83. if (thePlaceTo == ThePlaceTo.imageDiamands || thePlaceTo == ThePlaceTo.imageGold)
  84. {
  85. if (Vector3.Distance(transform.position, playerTransform.position) <= )
  86. {
  87. Destroy(this.gameObject);
  88. }
  89. return;
  90. }
  91. if (transform.position == playerTransform.position)
  92. {
  93. Destroy(this.gameObject);
  94. }
  95.  
  96. timeVal2 = InistStar(timeVal2, defineTime2, star2);
  97. }
  98. else
  99. {
  100. transform.localScale += new Vector3(Time.deltaTime * , Time.deltaTime * , Time.deltaTime * );
  101. if (bossPrize)
  102. {
  103. if (timeVal3 <= 0.3f)
  104. {
  105. timeVal3 += Time.deltaTime;
  106. transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
  107. }
  108.  
  109. }
  110. }
  111.  
  112. }
  113.  
  114. private float InistStar(float timeVals, float defineTimes, GameObject stars)
  115. {
  116.  
  117. if (timeVals >= defineTimes)
  118. {
  119. Instantiate(stars, this.transform.position, Quaternion.Euler(this.transform.eulerAngles.x, this.transform.eulerAngles.y, this.transform.eulerAngles.z + Random.Range(-40f, 40f)));
  120. timeVals = ;
  121. }
  122. else
  123. {
  124. timeVals += Time.deltaTime;
  125. }
  126.  
  127. return timeVals;
  128. }
  129. }

Gold  Prefabs/Item/Gold

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 美人鱼
  6. /// </summary>
  7. public class Missile : MonoBehaviour {
  8.  
  9. //属性
  10. public int hp=;
  11. public int GetGold = ;
  12. public float moveSpeed=;
  13.  
  14. //引用
  15. public GameObject gold;
  16. private GameObject fire;
  17. private GameObject ice;
  18. private Animator iceAni;
  19. private Animator gameObjectAni;
  20. public GameObject deadEeffect;
  21. private SpriteRenderer sr;
  22. //计时器
  23. private float rotateTime;
  24.  
  25. //开关
  26. private bool hasIce = false;
  27. private float timeVal;
  28.  
  29. // Use this for initialization
  30. void Start () {
  31. fire = transform.Find("Fire").gameObject;
  32. ice = transform.Find("Ice").gameObject;
  33. iceAni = ice.transform.GetComponent<Animator>();
  34. gameObjectAni = GetComponent<Animator>();
  35. sr = GetComponent<SpriteRenderer>();
  36. Destroy(this.gameObject, );
  37. }
  38.  
  39. // Update is called once per frame
  40. void Update () {
  41. if (timeVal >= )
  42. {
  43. sr.color -= new Color(, , , Time.deltaTime);
  44. }
  45. else
  46. {
  47. timeVal += Time.deltaTime;
  48. }
  49. //冰冻效果
  50. if (Gun.Instance.Ice)
  51. {
  52. gameObjectAni.enabled = false;
  53. ice.SetActive(true);
  54. if (!hasIce)
  55. {
  56. iceAni.SetTrigger("Ice");
  57. hasIce = true;
  58. }
  59.  
  60. }
  61. else
  62. {
  63. gameObjectAni.enabled = true;
  64. hasIce = false;
  65. ice.SetActive(false);
  66. }
  67.  
  68. //灼烧效果
  69. if (Gun.Instance.Fire)
  70. {
  71. fire.SetActive(true);
  72.  
  73. }
  74. else
  75. {
  76. fire.SetActive(false);
  77. }
  78.  
  79. if (Gun.Instance.Ice)
  80. {
  81. return;
  82. }
  83. transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
  84. if (rotateTime >= )
  85. {
  86. transform.Rotate(transform.forward * Random.Range(, ), Space.World);
  87. rotateTime = ;
  88. }
  89. else
  90. {
  91. rotateTime += Time.deltaTime;
  92. }
  93. }
  94.  
  95. public void Lucky(int attckValue)
  96. {
  97.  
  98. Gun.Instance.GoldChange(GetGold);
  99. Instantiate(gold, transform.position, transform.rotation);
  100. if (Gun.Instance.Fire)
  101. {
  102. attckValue *= ;
  103. }
  104. hp -= attckValue;
  105. if (hp<=)
  106. {
  107. Instantiate(deadEeffect, transform.position, transform.rotation);
  108. gameObjectAni.SetTrigger("Die");
  109. Invoke("Prize", 0.7f);
  110.  
  111. }
  112. }
  113. private void Prize()
  114. {
  115. Gun.Instance.GoldChange(GetGold * );
  116. for (int i = ; i < ; i++)
  117. {
  118. Instantiate(gold, transform.position + new Vector3(-5f + i, , ), transform.rotation);
  119. }
  120. Destroy(this.gameObject);
  121. }
  122. }

Missile  Prefabs/Item/Missile

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. /// <summary>
  5. /// 贝壳
  6. /// </summary>
  7. public class Shell : MonoBehaviour {
  8. //计时器
  9. private float rotateTime;
  10. private float timeVal = ;//无敌状态计时器
  11.  
  12. //属性
  13. public float moveSpeed = ;
  14.  
  15. //开关
  16. private bool isDeffend=true;
  17. private bool hasIce = false;
  18.  
  19. //引用
  20. public GameObject card;
  21. private GameObject fire;
  22. private GameObject ice;
  23. private Animator iceAni;
  24. private Animator gameObjectAni;
  25. private SpriteRenderer sr;
  26. private float timeVals;
  27.  
  28. // Use this for initialization
  29. void Start () {
  30. fire = transform.Find("Fire").gameObject;
  31. ice = transform.Find("Ice").gameObject;
  32. iceAni = ice.transform.GetComponent<Animator>();
  33. gameObjectAni = GetComponent<Animator>();
  34. sr = GetComponent<SpriteRenderer>();
  35. Destroy(this.gameObject,);
  36. }
  37.  
  38. // Update is called once per frame
  39. void Update () {
  40.  
  41. if (timeVals >= )
  42. {
  43. sr.color -= new Color(, , , Time.deltaTime);
  44. }
  45. else
  46. {
  47. timeVals += Time.deltaTime;
  48. }
  49. //灼烧效果
  50. if (Gun.Instance.Fire)
  51. {
  52. fire.SetActive(true);
  53.  
  54. }
  55. else
  56. {
  57. fire.SetActive(false);
  58. }
  59. //冰冻效果
  60. if (Gun.Instance.Ice)
  61. {
  62. gameObjectAni.enabled = false;
  63. ice.SetActive(true);
  64. if (!hasIce)
  65. {
  66. iceAni.SetTrigger("Ice");
  67. hasIce = true;
  68. }
  69.  
  70. }
  71. else
  72. {
  73. gameObjectAni.enabled = true;
  74. hasIce = false;
  75. ice.SetActive(false);
  76. }
  77.  
  78. if (Gun.Instance.Ice)
  79. {
  80. return;
  81. }
  82. transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
  83. if (rotateTime >= )
  84. {
  85. transform.Rotate(transform.forward * Random.Range(, ), Space.World);
  86. rotateTime = ;
  87. }
  88. else
  89. {
  90. rotateTime += Time.deltaTime;
  91. }
  92. if (timeVal<)
  93. {
  94.  
  95. timeVal += Time.deltaTime;
  96. }
  97. else if (timeVal>=&&timeVal<1.5)
  98. {
  99.  
  100. timeVal += Time.deltaTime;
  101. isDeffend = false;
  102. }
  103. else if (timeVal>=1.5)
  104. {
  105.  
  106. isDeffend = true;
  107. timeVal = ;
  108. }
  109. }
  110.  
  111. public void GetEffects()
  112. {
  113. if (isDeffend)
  114. {
  115.  
  116. return;
  117. }
  118. else
  119. {
  120. int num = Random.Range(, );
  121.  
  122. switch (num)
  123. {
  124. case :Gun.Instance.CanShootForFree();
  125. break;
  126. case :Gun.Instance.CanGetDoubleGold();
  127. break;
  128. case :Gun.Instance.CanShootNoCD();
  129. break;
  130. default:
  131. break;
  132. }
  133. GameObject go= Instantiate(card, transform.position, card.transform.rotation) as GameObject;
  134. go.GetComponent<Card>().num = num;
  135. Destroy(this.gameObject);
  136. }
  137. }
  138. }

Shell  Prefabs/Item/Shell

Player

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. /// <summary>
  7. /// 枪
  8. /// </summary>
  9.  
  10. public class Gun : MonoBehaviour
  11. {
  12.  
  13. //属性
  14. public int gold = ;
  15. public int diamands = ;
  16. public int gunLevel = ;
  17. private float rotateSpeed = 5f;
  18. public float attackCD = ;
  19. private float GunCD = ;
  20. public int level = ;
  21.  
  22. //引用
  23.  
  24. public AudioClip[] bullectAudios;
  25. private AudioSource bullectAudio;
  26. public Transform attackPos;
  27. public GameObject[] Bullects;
  28. public GameObject net;
  29. public GunChange[] gunChange;
  30.  
  31. public Transform goldPlace;
  32. public Transform diamondsPlace;
  33. public Transform imageGoldPlace;
  34. public Transform imageDiamandsPlace;
  35.  
  36. public Text goldText;
  37. public Text diamandsText;
  38.  
  39. //开关
  40. private bool canShootForFree = false;
  41. private bool canGetDoubleGold = false;
  42. public bool canShootNoCD = false;
  43. public bool canChangeGun = true;
  44. public bool bossAttack = false;
  45. public bool Fire = false;
  46. public bool Ice = false;
  47. public bool Butterfly = false;
  48. public bool attack = false;
  49.  
  50. public bool changeAudio;
  51.  
  52. private static Gun instance;
  53. public static Gun Instance
  54. {
  55. get
  56. {
  57. return instance;
  58. }
  59.  
  60. set
  61. {
  62. instance = value;
  63. }
  64. }
  65.  
  66. private void Awake()
  67. {
  68. instance = this;
  69. gold = ;
  70. diamands = ;
  71. level = ;
  72. bullectAudio = GetComponent<AudioSource>();
  73. }
  74.  
  75. // Use this for initialization
  76. void Start()
  77. {
  78.  
  79. }
  80.  
  81. // Update is called once per frame
  82. void Update()
  83. {
  84.  
  85. goldText.text = gold.ToString();
  86. diamandsText.text = diamands.ToString();
  87.  
  88. //旋转枪的方法
  89.  
  90. RotateGun();
  91.  
  92. if (GunCD <= )
  93. {
  94. canChangeGun = true;
  95. GunCD = ;
  96.  
  97. }
  98. else
  99. {
  100. GunCD -= Time.deltaTime;
  101. }
  102.  
  103. //攻击的方法
  104.  
  105. if (canShootNoCD)
  106. {
  107. Attack();
  108. attack = true;
  109. return;
  110. }
  111.  
  112. if (attackCD >= - gunLevel * 0.3)
  113. {
  114. Attack();
  115. attack = true;
  116. }
  117. else
  118. {
  119. attackCD += Time.deltaTime;
  120. }
  121. }
  122.  
  123. /// <summary>
  124. /// 以下是方法的定义
  125. /// </summary>
  126.  
  127. //旋转枪
  128.  
  129. private void RotateGun()
  130. {
  131.  
  132. float h = Input.GetAxisRaw("Mouse Y");
  133. float v = Input.GetAxisRaw("Mouse X");
  134.  
  135. transform.Rotate(-Vector3.forward * v * rotateSpeed);
  136. transform.Rotate(Vector3.forward * h * rotateSpeed);
  137.  
  138. ClampAngle();
  139. //245,115
  140. }
  141.  
  142. //换枪的方法
  143.  
  144. public void UpGun()
  145. {
  146. gunLevel += ;
  147. if (gunLevel == )
  148. {
  149. gunLevel = ;
  150. }
  151. gunChange[].ToGray();
  152. gunChange[].ToGray();
  153. canChangeGun = false;
  154. }
  155.  
  156. public void DownGun()
  157. {
  158. gunLevel -= ;
  159. if (gunLevel == )
  160. {
  161. gunLevel = ;
  162. }
  163. gunChange[].ToGray();
  164. gunChange[].ToGray();
  165. canChangeGun = false;
  166. }
  167.  
  168. //限制角度
  169. private void ClampAngle()
  170. {
  171. float y = transform.eulerAngles.y;
  172. if (y <= )
  173. {
  174. y = ;
  175. }
  176. else if (y >= )
  177. {
  178. y = ;
  179. }
  180.  
  181. transform.eulerAngles = new Vector3(transform.eulerAngles.x, y, transform.eulerAngles.z);
  182. }
  183.  
  184. //攻击方法
  185.  
  186. private void Attack()
  187. {
  188.  
  189. if (Input.GetMouseButtonDown())
  190. {
  191.  
  192. bullectAudio.clip = bullectAudios[gunLevel - ];
  193. bullectAudio.Play();
  194.  
  195. if (Butterfly)
  196. {
  197. Instantiate(Bullects[gunLevel - ], attackPos.position, attackPos.rotation * Quaternion.Euler(, , ));
  198. Instantiate(Bullects[gunLevel - ], attackPos.position, attackPos.rotation * Quaternion.Euler(, , -));
  199. }
  200.  
  201. Instantiate(Bullects[gunLevel - ], attackPos.position, attackPos.rotation);
  202.  
  203. if (!canShootForFree)
  204. {
  205. GoldChange(- - (gunLevel - ) * );
  206.  
  207. }
  208. attackCD = ;
  209. attack = false;
  210. }
  211.  
  212. }
  213.  
  214. //增减金钱
  215.  
  216. public void GoldChange(int number)
  217. {
  218. if (canGetDoubleGold)
  219. {
  220. if (number > )
  221. {
  222. number *= ;
  223. }
  224. }
  225.  
  226. gold += number;
  227. }
  228.  
  229. //增减钻石
  230.  
  231. public void DiamandsChange(int number)
  232. {
  233.  
  234. diamands += number;
  235. }
  236.  
  237. /// <summary>
  238. /// 贝壳触发的一些效果方法
  239. /// </summary>
  240.  
  241. public void CanShootForFree()
  242. {
  243. canShootForFree = true;
  244. Invoke("CantShootForFree", );
  245. }
  246.  
  247. public void CantShootForFree()
  248. {
  249. canShootForFree = false;
  250. }
  251.  
  252. public void CanGetDoubleGold()
  253. {
  254. canGetDoubleGold = true;
  255. Invoke("CantGetDoubleGold", );
  256. }
  257.  
  258. public void CantGetDoubleGold()
  259. {
  260. canGetDoubleGold = false;
  261. }
  262.  
  263. public void CanShootNoCD()
  264. {
  265. canShootNoCD = true;
  266. Invoke("CantShootNoCD", );
  267. }
  268.  
  269. public void CantShootNoCD()
  270. {
  271. canShootNoCD = false;
  272. }
  273.  
  274. //boss攻击的方法
  275. public void BossAttack()
  276. {
  277. bossAttack = true;
  278. }
  279. }

Gun  Fish/PlayerManager

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. /// <summary>
  7. /// 切枪的按钮
  8. /// </summary>
  9. public class GunChange : MonoBehaviour
  10. {
  11.  
  12. public bool add;
  13. private Button button;
  14. private Image image;
  15. public Sprite[] buttonSprites;//0.+ 1.灰色的+ 2.- 3.灰色的-
  16.  
  17. // Use this for initialization
  18. void Start()
  19. {
  20. button = transform.GetComponent<Button>();
  21. button.onClick.AddListener(ChangeGunLevel);
  22. image = GetComponent<Image>();
  23.  
  24. }
  25.  
  26. // Update is called once per frame
  27. void Update()
  28. {
  29. if (Gun.Instance.canChangeGun)
  30. {
  31. if (add)
  32. {
  33. image.sprite = buttonSprites[];
  34.  
  35. }
  36. else
  37. {
  38. image.sprite = buttonSprites[];
  39. }
  40.  
  41. }
  42. }
  43.  
  44. public void ChangeGunLevel()
  45. {
  46. if (Gun.Instance.canChangeGun)
  47. {
  48. if (add)
  49. {
  50. Gun.Instance.UpGun();
  51. }
  52. else
  53. {
  54. Gun.Instance.DownGun();
  55. }
  56. }
  57. }
  58.  
  59. public void ToGray()
  60. {
  61. if (add)
  62. {
  63. image.sprite = buttonSprites[];
  64.  
  65. }
  66. else
  67. {
  68. image.sprite = buttonSprites[];
  69.  
  70. }
  71.  
  72. }
  73.  
  74. }

GunChange  Fish/Canvas/UI_LeftTable/AddGunLevel

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Bullect : MonoBehaviour {
  5.  
  6. public GameObject explosions;
  7.  
  8. public GameObject star;
  9. public GameObject star1;
  10. public GameObject star2;
  11. public float moveSpeed;
  12. private float timeVal;
  13. public float defineTime;
  14. private float timeVal1;
  15. public float defineTime1;
  16. private float timeVal2;
  17. public float defineTime2;
  18. public Transform CreatePos;
  19. public GameObject net;
  20. public int level;
  21.  
  22. public float attackValue;
  23.  
  24. // Use this for initialization
  25. void Start () {
  26.  
  27. }
  28.  
  29. // Update is called once per frame
  30. void Update () {
  31. timeVal=InistStar(timeVal,defineTime,star);
  32. timeVal1=InistStar(timeVal1,defineTime1,star1);
  33. timeVal2=InistStar(timeVal2,defineTime2,star2);
  34. transform.Translate(transform.up*moveSpeed*Time.deltaTime,Space.World);
  35. }
  36.  
  37. private float InistStar(float timeVals,float defineTimes,GameObject stars)
  38. {
  39.  
  40. if (timeVals>=defineTimes) {
  41. Instantiate(stars, CreatePos.transform.position, Quaternion.Euler(CreatePos.transform.eulerAngles.x, CreatePos.transform.eulerAngles.y, CreatePos.transform.eulerAngles.z+Random.Range(-40f,40f)));
  42. timeVals=;
  43. }
  44. else {
  45. timeVals+=Time.deltaTime;
  46. }
  47.  
  48. return timeVals;
  49. }
  50.  
  51. private void OnTriggerEnter(Collider other)
  52. {
  53. if (other.tag == "fish" || other.tag == "boss")
  54. {
  55. other.SendMessage("TakeDamage", attackValue);
  56. GameObject go = Instantiate(net, transform.position + new Vector3(, , ), transform.rotation);
  57. go.transform.localScale = new Vector3(level, level, level);
  58. Instantiate(explosions, transform.position, transform.rotation);
  59. Destroy(this.gameObject);
  60. }
  61. else if (other.tag == "missile")
  62. {
  63. other.SendMessage("Lucky", attackValue);
  64. GameObject go = Instantiate(net, transform.position + new Vector3(, , ), transform.rotation);
  65. go.transform.localScale = new Vector3(level, level, level);
  66. Instantiate(explosions, transform.position, transform.rotation);
  67. Destroy(this.gameObject);
  68. }
  69. else if (other.tag == "Shell")
  70. {
  71. other.SendMessage("GetEffects");
  72. GameObject go = Instantiate(net, transform.position + new Vector3(, , ), transform.rotation);
  73. go.transform.localScale = new Vector3(level, level, level);
  74. Instantiate(explosions, transform.position, transform.rotation);
  75. Destroy(this.gameObject);
  76. }
  77. else if (other.tag == "Qipao")
  78. {
  79. GameObject go = Instantiate(net, transform.position + new Vector3(, , ), transform.rotation);
  80. go.transform.localScale = new Vector3(level, level, level);
  81. Instantiate(explosions, transform.position, transform.rotation);
  82. Destroy(this.gameObject);
  83. }
  84. /*else*/
  85. if (other.tag == "Wall")
  86. {
  87. float angleValue = Vector3.Angle(transform.up, other.transform.up);
  88. if (angleValue < )
  89. {
  90. transform.eulerAngles += new Vector3(, , *angleValue);
  91. }
  92. else if (Vector3.Angle(transform.up, other.transform.up) > )
  93. {
  94. transform.eulerAngles -= new Vector3(, , - * angleValue);
  95. }
  96. else
  97. {
  98. transform.eulerAngles += new Vector3(, , );
  99. }
  100. }
  101. }
  102. }

Bullet  Prefabs/Player/Bullet1,2,3

  PlayerUI

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// 灼烧
  7. /// </summary>
  8. public class Fire : MonoBehaviour
  9. {
  10.  
  11. private Button but;
  12. private float timeVal = ;
  13. private bool canUse = true;
  14. private float totalTime = ;
  15.  
  16. public Slider cdSlider;
  17. private int reduceDiamands;
  18.  
  19. private void Awake()
  20. {
  21. but = transform.GetComponent<Button>();
  22. but.onClick.AddListener(Attack);
  23.  
  24. }
  25.  
  26. // Use this for initialization
  27.  
  28. void Start()
  29. {
  30. reduceDiamands = ;
  31. }
  32.  
  33. // Update is called once per frame
  34. void Update()
  35. {
  36. if (timeVal >= )
  37. {
  38. timeVal = ;
  39. }
  40. cdSlider.value = timeVal / totalTime;
  41. if (timeVal >= )
  42. {
  43.  
  44. canUse = true;
  45. cdSlider.transform.Find("Background").gameObject.SetActive(false);
  46. }
  47. else
  48. {
  49.  
  50. timeVal += Time.deltaTime;
  51. }
  52. }
  53.  
  54. private void Attack()
  55. {
  56. if (canUse)
  57. {
  58. if (!Gun.Instance.Ice && !Gun.Instance.Fire)
  59. {
  60.  
  61. if (Gun.Instance.diamands <= reduceDiamands)
  62. {
  63. return;
  64. }
  65.  
  66. Gun.Instance.DiamandsChange(-reduceDiamands);
  67. Gun.Instance.Fire = true;
  68. canUse = false;
  69. cdSlider.transform.Find("Background").gameObject.SetActive(true);
  70. timeVal = ;
  71. Invoke("CloseFire", );
  72. }
  73. }
  74.  
  75. }
  76.  
  77. //关闭必杀的方法
  78. private void CloseFire()
  79. {
  80. Gun.Instance.Fire = false;
  81. }
  82.  
  83. }

Fire  Fish/Canvas/UI_Skills/Img_Fire/But_Fire

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. /// <summary>
  7. /// 冰冻
  8. /// </summary>
  9. public class Ice : MonoBehaviour
  10. {
  11.  
  12. private float timeVal = ;
  13. private bool canUse = true;
  14.  
  15. public Slider cdSlider;
  16. private float totalTime = ;
  17. Button but;
  18. private AudioSource fireAudio;
  19. private int reduceDiamands;
  20. // Use this for initialization
  21. private void Awake()
  22. {
  23. but = transform.GetComponent<Button>();
  24. but.onClick.AddListener(ice);
  25. fireAudio = GetComponent<AudioSource>();
  26. }
  27.  
  28. void Start()
  29. {
  30. reduceDiamands = ;
  31. }
  32.  
  33. private void Update()
  34. {
  35. if (timeVal >= )
  36. {
  37. timeVal = ;
  38. }
  39. cdSlider.value = timeVal / totalTime;
  40. if (timeVal >= )
  41. {
  42. cdSlider.transform.Find("Background").gameObject.SetActive(false);
  43. canUse = true;
  44. }
  45. else
  46. {
  47.  
  48. timeVal += Time.deltaTime;
  49. }
  50. }
  51.  
  52. private void ice()
  53. {
  54. //必杀的方法
  55. if (canUse)
  56. {
  57. if (!Gun.Instance.Fire && !Gun.Instance.Ice)
  58. {
  59.  
  60. if (Gun.Instance.diamands <= reduceDiamands)
  61. {
  62. return;
  63. }
  64. if (fireAudio.isPlaying)
  65. {
  66. return;
  67. }
  68. fireAudio.Play();
  69. Gun.Instance.DiamandsChange(-reduceDiamands);
  70. Gun.Instance.Ice = true;
  71. canUse = false;
  72. cdSlider.transform.Find("Background").gameObject.SetActive(true);
  73. timeVal = ;
  74. Invoke("CloseIce", );
  75. }
  76. }
  77.  
  78. }
  79.  
  80. //关闭必杀的方法
  81. private void CloseIce()
  82. {
  83.  
  84. Gun.Instance.Ice = false;
  85. }
  86. }

Ice  Fish/Canvas/UI_Skills/UI_Ice/But_Ice

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// 散弹按钮
  7. /// </summary>
  8. public class ButterFly : MonoBehaviour
  9. {
  10.  
  11. Button but;
  12.  
  13. private float timeVal = ;
  14. private bool canUse = true;
  15. private float totalTime = ;
  16. public GameObject uiView;
  17.  
  18. public Slider cdSlider;
  19. private int reduceDiamands;
  20.  
  21. private void Awake()
  22. {
  23. but = transform.GetComponent<Button>();
  24. but.onClick.AddListener(Fire);
  25.  
  26. }
  27.  
  28. void Start()
  29. {
  30. reduceDiamands = ;
  31. }
  32.  
  33. // Update is called once per frame
  34. void Update()
  35. {
  36. if (timeVal >= )
  37. {
  38. timeVal = ;
  39. }
  40. cdSlider.value = timeVal / totalTime;
  41. if (timeVal >= )
  42. {
  43.  
  44. canUse = true;
  45. cdSlider.transform.Find("Background").gameObject.SetActive(false);
  46. }
  47. else
  48. {
  49.  
  50. timeVal += Time.deltaTime;
  51. }
  52. }
  53.  
  54. private void Fire()
  55. {
  56. if (canUse)
  57. {
  58.  
  59. if (Gun.Instance.diamands <= reduceDiamands)
  60. {
  61. return;
  62. }
  63. Gun.Instance.DiamandsChange(-reduceDiamands);
  64.  
  65. Gun.Instance.Butterfly = true;
  66. canUse = false;
  67. cdSlider.transform.Find("Background").gameObject.SetActive(true);
  68. timeVal = ;
  69. Invoke("CloseFire", );
  70. uiView.SetActive(true);
  71.  
  72. }
  73.  
  74. }
  75.  
  76. //关闭必杀的方法
  77. private void CloseFire()
  78. {
  79. uiView.SetActive(false);
  80. Gun.Instance.Butterfly = false;
  81. }
  82.  
  83. }

ButterFly  Fish/Canvas/UI_Skills/UI_ButterflyShoot/But_ButterflyShoot

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// 负责UI显示的枪
  7. /// </summary>
  8. public class GunImage : MonoBehaviour
  9. {
  10.  
  11. public Sprite[] Guns;
  12. private Image img;
  13.  
  14. public Transform idlePos;
  15. public Transform attackPos;
  16.  
  17. private float rotateSpeed = 5f;
  18.  
  19. private void Awake()
  20. {
  21. img = transform.GetComponent<Image>();
  22. }
  23. // Use this for initialization
  24. void Start()
  25. {
  26.  
  27. }
  28.  
  29. // Update is called once per frame
  30. void Update()
  31. {
  32. //旋转枪的方法
  33.  
  34. RotateGun();
  35. img.sprite = Guns[Gun.Instance.gunLevel - ];
  36.  
  37. //攻击的方法
  38.  
  39. if (Gun.Instance.attack)
  40. {
  41. if (Input.GetMouseButtonDown())
  42. {
  43. attack();
  44. }
  45. }
  46.  
  47. }
  48.  
  49. private void attack()
  50. {
  51.  
  52. transform.position = Vector3.Lerp(transform.position, attackPos.position, 0.5f);
  53. Invoke("idle", 0.4f);
  54. }
  55. private void idle()
  56. {
  57.  
  58. transform.position = Vector3.Lerp(transform.position, idlePos.position, 0.2f);
  59.  
  60. }
  61. //旋转枪
  62.  
  63. private void RotateGun()
  64. {
  65.  
  66. float h = Input.GetAxisRaw("Mouse Y");
  67. float v = Input.GetAxisRaw("Mouse X");
  68.  
  69. transform.Rotate(-Vector3.forward * v * rotateSpeed);
  70. transform.Rotate(Vector3.forward * h * rotateSpeed);
  71.  
  72. ClampAngle();
  73.  
  74. }
  75.  
  76. //限制角度
  77. private void ClampAngle()
  78. {
  79. float z = transform.eulerAngles.z;
  80. if (z <= )
  81. {
  82. z = ;
  83. }
  84. else if (z >= )
  85. {
  86. z = ;
  87. }
  88.  
  89. transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, z);
  90. }
  91. }

GunImage  Fish/Canvas/Img_Gun

  UI

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. /// <summary>
  5. /// 产生UI泡泡
  6. /// </summary>
  7. public class CreatePao : MonoBehaviour
  8. {
  9.  
  10. public GameObject pao;
  11. public Transform panel;
  12. private float timeVal = ;
  13.  
  14. // Use this for initialization
  15. void Start()
  16. {
  17.  
  18. }
  19.  
  20. // Update is called once per frame
  21. void Update()
  22. {
  23.  
  24. if (timeVal >= )
  25. {
  26. for (int i = ; i < ; i++)
  27. {
  28. Invoke("InstPao", );
  29. }
  30. timeVal = ;
  31. }
  32. else
  33. {
  34. timeVal += Time.deltaTime;
  35. }
  36. }
  37.  
  38. private void InstPao()
  39. {
  40.  
  41. GameObject itemGo = Instantiate(pao, transform.position, Quaternion.Euler(, , Random.Range(-, ))) as GameObject;
  42. itemGo.transform.SetParent(panel);
  43. }
  44. }

CreatePao  Main/Canvas/Panel/CreatePao

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.SceneManagement;
  6. public class StartGame : MonoBehaviour {
  7.  
  8. private Button but;
  9.  
  10. // Use this for initialization
  11. void Start () {
  12. but = GetComponent<Button>();
  13. but.onClick.AddListener(StartGames);
  14. }
  15.  
  16. private void StartGames()
  17. {
  18. SceneManager.LoadScene();
  19. }
  20.  
  21. // Update is called once per frame
  22. void Update () {
  23.  
  24. }
  25. }

StartGame  Main/Canvas/Panel/UI_StartGame/But_StartGame

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using UnityEngine.SceneManagement;
  7. public class LoadGame : MonoBehaviour {
  8.  
  9. public Slider processView;
  10.  
  11. // Use this for initialization
  12. void Start () {
  13. LoadGameMethod();
  14.  
  15. }
  16.  
  17. // Update is called once per frame
  18. void Update () {
  19.  
  20. }
  21. public void LoadGameMethod()
  22. {
  23. StartCoroutine(StartLoading_4());
  24. }
  25.  
  26. private IEnumerator StartLoading_4(int scene)
  27. {
  28. int displayProgress = ;
  29. int toProgress = ;
  30. AsyncOperation op = SceneManager.LoadSceneAsync(scene);
  31. op.allowSceneActivation = false;
  32. while (op.progress < 0.9f)
  33. {
  34. toProgress = (int)op.progress * ;
  35. while (displayProgress < toProgress)
  36. {
  37. ++displayProgress;
  38. SetLoadingPercentage(displayProgress);
  39. yield return new WaitForEndOfFrame();
  40. }
  41. }
  42.  
  43. toProgress = ;
  44. while (displayProgress < toProgress)
  45. {
  46. ++displayProgress;
  47. SetLoadingPercentage(displayProgress);
  48. yield return new WaitForEndOfFrame();
  49. }
  50. op.allowSceneActivation = true;
  51. }
  52.  
  53. private void SetLoadingPercentage(float v)
  54. {
  55. processView.value = v / ;
  56. }
  57.  
  58. }

LoadGame  Loading/Canvas/Panel/LoadGame

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// 宝藏
  7. /// </summary>
  8. public class Treasour : MonoBehaviour
  9. {
  10.  
  11. private Button but;
  12. private Image img;
  13.  
  14. public GameObject gold;
  15. public GameObject diamands;
  16. public GameObject cdView;
  17.  
  18. public Transform cavas;
  19. private bool isDrease;
  20.  
  21. private void Awake()
  22. {
  23. but = GetComponent<Button>();
  24. but.onClick.AddListener(OpenTreasour);
  25. img = GetComponent<Image>();
  26. }
  27.  
  28. void OpenTreasour()
  29. {
  30. if (img.color.a != )
  31. {
  32. return;
  33. }
  34. cdView.SetActive(true);
  35. Gun.Instance.GoldChange(Random.Range(, ));
  36. Gun.Instance.DiamandsChange(Random.Range(, ));
  37. CreatePrize();
  38. isDrease = true;
  39. }
  40. private void CreatePrize()
  41. {
  42. for (int i = ; i < ; i++)
  43. {
  44. GameObject go = Instantiate(gold, transform.position + new Vector3(-10f + i * , , ), transform.rotation);
  45. go.transform.SetParent(cavas);
  46. GameObject go1 = Instantiate(diamands, transform.position + new Vector3(, , ) + new Vector3(-10f + i * , , ), transform.rotation);
  47. go1.transform.SetParent(cavas);
  48. }
  49. }
  50.  
  51. // Use this for initialization
  52. void Start()
  53. {
  54.  
  55. }
  56.  
  57. // Update is called once per frame
  58. void Update()
  59. {
  60. if (isDrease)
  61. {
  62. img.color -= new Color(, , , Time.deltaTime * );
  63. if (img.color.a <= 0.2)
  64. {
  65. img.color = new Color(img.color.r, img.color.g, img.color.b, );
  66. isDrease = false;
  67. }
  68. }
  69. else
  70. {
  71. img.color += new Color(, , , Time.deltaTime * 0.01f);
  72. if (img.color.a >= 0.9)
  73. {
  74. img.color = new Color(img.color.r, img.color.g, img.color.b, );
  75. cdView.SetActive(false);
  76. }
  77. }
  78.  
  79. }
  80. }

Treasour  Fish/Canvas/UI_Treasour/But_Treasour

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. /// <summary>
  6. /// 地图背景
  7. /// </summary>
  8. public class Ground : MonoBehaviour
  9. {
  10.  
  11. private MeshRenderer mr;
  12.  
  13. public Material[] materialList;
  14.  
  15. private AudioSource audioSource;
  16. public AudioClip[] audioClips;
  17.  
  18. // Use this for initialization
  19. void Start()
  20. {
  21. mr = GetComponent<MeshRenderer>();
  22. audioSource = GetComponent<AudioSource>();
  23. }
  24.  
  25. // Update is called once per frame
  26. void Update()
  27. {
  28. if (Gun.Instance.changeAudio)
  29. {
  30. audioSource.clip = audioClips[Gun.Instance.level - ];
  31. audioSource.Play();
  32. Gun.Instance.changeAudio = false;
  33. }
  34. if (Gun.Instance.level == )
  35. {
  36. if (Gun.Instance.Fire)
  37. {
  38. mr.material = materialList[];
  39. }
  40. else if (Gun.Instance.Ice)
  41. {
  42. mr.material = materialList[];
  43. }
  44. else
  45. {
  46. mr.material = materialList[];
  47. }
  48. }
  49. else if (Gun.Instance.level == )
  50. {
  51. if (Gun.Instance.Fire)
  52. {
  53. mr.material = materialList[];
  54. }
  55. else if (Gun.Instance.Ice)
  56. {
  57. mr.material = materialList[];
  58. }
  59. else
  60. {
  61. mr.material = materialList[];
  62. }
  63. }
  64. else if (Gun.Instance.level == )
  65. {
  66. if (Gun.Instance.Fire)
  67. {
  68. mr.material = materialList[];
  69. }
  70. else if (Gun.Instance.Ice)
  71. {
  72. mr.material = materialList[];
  73. }
  74. else
  75. {
  76. mr.material = materialList[];
  77. }
  78. }
  79. }
  80. }

Ground  Fish/Plane

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class Mylight : MonoBehaviour {
  6.  
  7. public Sprite[] lights;
  8. private Image img;
  9. private int i;
  10. private float timeVal;
  11.  
  12. private void Awake()
  13. {
  14. img = GetComponent<Image>();
  15.  
  16. }
  17.  
  18. // Use this for initialization
  19. void Start () {
  20.  
  21. }
  22.  
  23. // Update is called once per frame
  24. void Update () {
  25. if (timeVal>=0.08f)
  26. {
  27. img.sprite = lights[i];
  28. i++;
  29. if (i == lights.Length)
  30. {
  31. i = ;
  32. }
  33. timeVal = ;
  34. }
  35. else
  36. {
  37. timeVal += Time.deltaTime;
  38. }
  39.  
  40. }
  41. }

Mylight  Fish/Canvas/Img_Gun/Img_GunEffectRight

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.SceneManagement;
  6. public class ReturnMain : MonoBehaviour {
  7.  
  8. private Button but;
  9.  
  10. // Use this for initialization
  11. void Start()
  12. {
  13. but = GetComponent<Button>();
  14. but.onClick.AddListener(StartGames);
  15. }
  16.  
  17. public void StartGames()
  18. {
  19. SceneManager.LoadScene();
  20. }
  21.  
  22. // Update is called once per frame
  23. void Update()
  24. {
  25.  
  26. }
  27. }

ReturnMain  Fish/Canvas/UI_ReturnMenu/But_ReturnMenu

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Star : MonoBehaviour {
  5.  
  6. public float moveSpeed=;
  7.  
  8. // Use this for initialization
  9. void Start () {
  10. Destroy(gameObject,Random.Range(0.4f,));
  11. }
  12.  
  13. // Update is called once per frame
  14. void Update () {
  15. //transform.Translate(-transform.right*moveSpeed*Time.deltaTime,Space.World);
  16. }
  17. }

Star  Prefabs/Effects/star...

  1. --1.1 点击宝箱领取的金币钻石太拥挤,分散一点。
  2.  
  3. local UnityEngine=CS.UnityEngine
  4. xlua.hotfix(CS.Treasour,'CreatePrize',function(self)
  5. for i=,, do
  6. local go=UnityEngine.GameObject.Instantiate(self.gold,self.transform.position+UnityEngine.Vector3(-+i*,,),self.transform.rotation)
  7. go.transform.SetParent(go.transform,self.cavas)
  8. local go1=UnityEngine.GameObject.Instantiate(self.diamands,self.transform.position+UnityEngine.Vector3(,,)+UnityEngine.Vector3(-+i*,,),self.transform.rotation)
  9. go1.transform.SetParent(go1.transform,self.cavas)
  10. end
  11. end)
  12.  
  13. --******************************************************************
  14.  
  15. --1.1 玩家金币钻石不够时没有相应处理。
  16.  
  17. xlua.private_accessible(CS.Gun)
  18. xlua.hotfix(CS.Gun,'Attack',function(self)
  19. if UnityEngine.Input.GetMouseButtonDown() then
  20.  
  21. --1.2 UI交互时不能发射子弹
  22.  
  23. if UnityEngine.EventSystems.EventSystem.current:IsPointerOverGameObject() then
  24. return
  25. end
  26.  
  27. --[[
  28. if self.gold<+(self.gunLevel-)* or gold== then
  29. return
  30. end
  31. --]]
  32.  
  33. --1.3 炮台3太强,且钻石没用处,不削弱,只有氪金才可使用
  34.  
  35. if self.gunLevel== and self.diamands< then
  36.  
  37. return
  38.  
  39. elseif self.gunLevel~= then
  40.  
  41. if self.gold<+(self.gunLevel-)* or gold== then
  42. return
  43. end
  44. end
  45.  
  46. self.bullectAudio.clip=self.bullectAudios[self.gunLevel-]
  47. self.bullectAudio:Play()
  48.  
  49. if self.Butterfly then
  50. UnityEngine.GameObject.Instantiate(self.Bullects[self.gunLevel-],self.attackPos.position,self.attackPos.rotation*UnityEngine.Quaternion.Euler(,,))
  51. UnityEngine.GameObject.Instantiate(self.Bullects[self.gunLevel-],self.attackPos.position,self.attackPos.rotation*UnityEngine.Quaternion.Euler(,,-))
  52. end
  53.  
  54. UnityEngine.GameObject.Instantiate(self.Bullects[self.gunLevel-],self.attackPos.position,self.attackPos.rotation)
  55.  
  56. if not self.canShootForFree then
  57. if self.gunLevel== then
  58. self:DiamandsChange(-)
  59. else
  60. self:GoldChange(--(self.gunLevel-)*)
  61. end
  62. end
  63. self.attackCD=
  64. self.attack=false
  65. end
  66.  
  67. end)
  68.  
  69. --******************************************************************
  70.  
  71. -- 1.2 技能扣钻石太多。
  72.  
  73. xlua.private_accessible(CS.Fire)
  74. xlua.hotfix(CS.Fire,'Start',function(self)
  75. self.reduceDiamands = ;
  76. end)
  77.  
  78. xlua.private_accessible(CS.Ice)
  79. xlua.hotfix(CS.Ice,'Start',function(self)
  80. self.reduceDiamands = ;
  81. end)
  82.  
  83. xlua.private_accessible(CS.ButterFly)
  84. xlua.hotfix(CS.ButterFly,'Start',function(self)
  85. self.reduceDiamands = ;
  86. end)
  87.  
  88. --*************************************************************
  89.  
  90. -- 1.2 boss撞击玩家数值变动一样且不是减少是增加。
  91.  
  92. local util=require 'util'
  93.  
  94. xlua.private_accessible(CS.Boss)
  95. util.hotfix_ex(CS.Boss,'Start',function(self)
  96. self.Start(self)
  97. self.m_reduceGold=self.m_reduceGold-
  98. end)
  99.  
  100. xlua.private_accessible(CS.DeffendBoss)
  101. util.hotfix_ex(CS.DeffendBoss,'Start',function(self)
  102. self.Start(self)
  103. self.m_reduceGold=self.m_reduceGold-
  104. end)
  105.  
  106. xlua.private_accessible(CS.InvisibleBoss)
  107. util.hotfix_ex(CS.InvisibleBoss,'Start',function(self)
  108. self.Start(self)
  109. self.m_reduceDiamond=self.m_reduceDiamond-
  110. end)
  111.  
  112. --********************************************************************
  113.  
  114. -- 1.3 boss撞击玩家当钻石金币不够时会产生负数。
  115.  
  116. util.hotfix_ex(CS.Gun,'GoldChange',function(self,number)
  117. self.GoldChange(self,number)
  118. if self.gold<-number then
  119. self.gold=
  120. return
  121. end
  122. end)
  123.  
  124. util.hotfix_ex(CS.Gun,'DiamandsChange',function(self,number)
  125. self.DiamandsChange(self,number)
  126. if self.diamands<-number then
  127. self.diamands=
  128. return
  129. end
  130. end)
  131.  
  132. --******************************************************************
  133.  
  134. -- 1.3 大鱼太多
  135.  
  136. local canCreateNewFish=true
  137. local changeMapTimeval=
  138.  
  139. xlua.hotfix(CS.CreateFish,'Start',function(self)
  140. --self.hotFixScript:LoadResource('level3fish3','gameobject\\enemy.ab')
  141. --self.hotFixScript:LoadResource('SeaWave','gameobject\\wave.ab')
  142. end)
  143.  
  144. xlua.private_accessible(CS.CreateFish)
  145. xlua.hotfix(CS.CreateFish,'Update',function(self)
  146.  
  147. -- 2.0 生成海浪
  148.  
  149. if canCreateNewFish then
  150.  
  151. if changeMapTimeval >= then
  152. go=CS.HotFixScript.GetGameObject('SeaWave')
  153. UnityEngine.GameObject.Instantiate(go)
  154. canCreateNewFish=false
  155. changeMapTimeval=
  156. else
  157. changeMapTimeval=changeMapTimeval+UnityEngine.Time.deltaTime
  158. end
  159. else
  160. return
  161. end
  162.  
  163. self:CreateALotOfFish()
  164.  
  165. --单种鱼的生成
  166. if self.ItemtimeVal>=0.5 then
  167.  
  168. --位置随机数
  169. self.num =UnityEngine.Mathf.Floor(UnityEngine.Random.Range(, )
  170. )
  171. --游戏物体随机数
  172. self.ItemNum =UnityEngine.Mathf.Floor(UnityEngine.Random.Range(, ))
  173.  
  174. local halfLength=self.fishList.Length/
  175.  
  176. local littlefishTypeIndex=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(,halfLength))
  177.  
  178. local bigfishTypeIndex=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(halfLength,self.fishList.Length))
  179.  
  180. local itemTypeIndex=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(,self.item.Length))
  181.  
  182. --产生气泡
  183. if self.ItemNum< then
  184.  
  185. self:CreateGameObject(self.item[])
  186.  
  187. end
  188.  
  189. if self.ItemNum <= then
  190. for i=,, do
  191. self:CreateGameObject(self.fishList[littlefishTypeIndex])
  192. end
  193. self:CreateGameObject(self.item[itemTypeIndex])
  194.  
  195. elseif self.ItemNum >= and self.ItemNum < then
  196. for i=,, do
  197. self:CreateGameObject(self.fishList[bigfishTypeIndex])
  198. end
  199. self:CreateGameObject(self.item[itemTypeIndex])
  200. --2.0 新鱼
  201. elseif self.ItemNum >= and self.ItemNum < then
  202.  
  203. newFish=CS.HotFixScript.GetGameObject('level3fish3')
  204. self:CreateGameObject(newFish)
  205.  
  206. elseif self.ItemNum >= and self.ItemNum < then
  207.  
  208. self:CreateGameObject(self.boss)
  209.  
  210. elseif self.ItemNum >= and self.ItemNum <= then
  211.  
  212. self:CreateGameObject(self.boss2)
  213.  
  214. elseif self.ItemNum== then
  215.  
  216. self:CreateGameObject(self.boss3)
  217.  
  218. else
  219.  
  220. self:CreateGameObject(self.item[]);
  221.  
  222. end
  223.  
  224. self.ItemtimeVal =
  225. else
  226.  
  227. self.ItemtimeVal =self.ItemtimeVal+CS.UnityEngine.Time.deltaTime;
  228. end
  229.  
  230. end)
  231.  
  232. --**********************************************************************************
  233.  
  234. -- 1.4 扑鱼是考虑了鱼的血量与子弹的伤害来模拟概率,这样玩家体验不好,要使用传统的概率来扑鱼。
  235.  
  236. xlua.private_accessible(CS.Fish)
  237. xlua.hotfix(CS.Fish,'TakeDamage',function(self,attackValue)
  238.  
  239. if UnityEngine.Gun.Instance.Fire then
  240.  
  241. attackValue=attackValue*;
  242.  
  243. end
  244. local catchValue=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(,))
  245. if catchValue<=(-(self.hp-attackValue))/ then
  246.  
  247. self.isDead = true
  248. for i=,, do
  249. UnityEngine.GameObject.Instantiate(self.pao, self.transform.position, UnityEngine.Quaternion.Euler(self.transform.eulerAngles + UnityEngine.Vector3(, * i, )))
  250. end
  251.  
  252. self.gameObjectAni:SetTrigger("Die")
  253. self:Invoke("Prize", 0.7)
  254. end
  255. end)
  256.  
  257. xlua.hotfix(CS.Boss,'TakeDamage',function(self,attackValue)
  258. if UnityEngine.Gun.Instance.Fire then
  259.  
  260. attackValue=attackValue*;
  261. end
  262.  
  263. local catchValue=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(,))
  264. if catchValue<=(attackValue*-self.hp/) then
  265.  
  266. UnityEngine.GameObject.Instantiate(self.deadEeffect, self.transform.position, self.transform.rotation)
  267. CS.Gun.Instance:GoldChange(self.GetGold * )
  268. CS.Gun.Instance:DiamandsChange(self.GetDiamands * )
  269.  
  270. for i=,, do
  271.  
  272. local itemGo =UnityEngine.GameObject.Instantiate(self.gold, self.transform.position, UnityEngine.Quaternion.Euler(self.transform.eulerAngles + UnityEngine.Vector3(, + * (i - ), )))
  273. itemGo:GetComponent('Gold').bossPrize = true
  274. end
  275. for i=,, do
  276.  
  277. local itemGo1 =UnityEngine.GameObject.Instantiate(self.diamands,self.transform.position, UnityEngine.Quaternion.Euler(self.transform.eulerAngles + UnityEngine.Vector3(, + * (i - ), )))
  278. itemGo1:GetComponent('Gold').bossPrize = true
  279. end
  280. UnityEngine.Object.Destroy(self.gameObject)
  281.  
  282. end
  283. end)
  284.  
  285. -- ***********************************************************************************
  286.  
  287. -- 1.4 炮台移动是根据鼠标的水平数值滑动来模拟跟随的,改为玩家按下ad键来旋转炮台
  288.  
  289. xlua.hotfix(CS.Gun,'RotateGun',function(self)
  290. if UnityEngine.Input.GetKey(UnityEngine.KeyCode.A) then
  291. self.transform:Rotate(UnityEngine.Vector3.forward * self.rotateSpeed)
  292. elseif UnityEngine.Input.GetKey(UnityEngine.KeyCode.D) then
  293. self.transform:Rotate(-UnityEngine.Vector3.forward * self.rotateSpeed)
  294. end
  295. self:ClampAngle()
  296. end)
  297.  
  298. xlua.private_accessible(CS.GunImage)
  299. xlua.hotfix(CS.GunImage,'RotateGun',function(self)
  300. if UnityEngine.Input.GetKey(UnityEngine.KeyCode.A) then
  301. self.transform:Rotate(UnityEngine.Vector3.forward * self.rotateSpeed)
  302. elseif UnityEngine.Input.GetKey(UnityEngine.KeyCode.D) then
  303. self.transform:Rotate(-UnityEngine.Vector3.forward * self.rotateSpeed)
  304. end
  305. self:ClampAngle()
  306. end)
  307.  
  308. -- 2.0 海浪
  309.  
  310. xlua.private_accessible(CS.HotFixEmpty)
  311. xlua.hotfix(CS.HotFixEmpty,'Start',function(self)
  312. self:Invoke("BehaviourMethod",)
  313. end)
  314.  
  315. xlua.hotfix(CS.HotFixEmpty,'Update',function(self)
  316. self.transform:Translate(-self.transform.right**UnityEngine.Time.deltaTime,UnityEngine.Space.World)
  317. end)
  318.  
  319. xlua.hotfix(CS.HotFixEmpty,'OnTriggerEnter',function(self,other)
  320. if other.tag~="Untagged" and other.tag~="Wall" then
  321. UnityEngine.Object.Destroy(other.gameObject)
  322. end
  323. end)
  324.  
  325. xlua.hotfix(CS.HotFixEmpty,'BehaviourMethod',function(self)
  326. CS.Gun.Instance.level=CS.Gun.Instance.level+
  327. if CS.Gun.Instance.level== then
  328. CS.Gun.Instance.level=
  329. end
  330. canCreateNewFish=true
  331. CS.Gun.Instance.changeAudio=true
  332. UnityEngine.Object.Destroy(self.gameObject)
  333.  
  334. end)
  335.  
  336. xlua.hotfix(CS.Treasour,'CreatePrize',nil)
  337.  
  338. xlua.hotfix(CS.Gun,'Attack',nil)
  339.  
  340. xlua.hotfix(CS.Ice,'Start',nil)
  341.  
  342. xlua.hotfix(CS.Fire,'Start',nil)
  343.  
  344. xlua.hotfix(CS.ButterFly,'Start',nil)
  345.  
  346. xlua.hotfix(CS.Boss,'Start',nil)
  347.  
  348. xlua.hotfix(CS.DeffendBoss,'Start',nil)
  349.  
  350. xlua.hotfix(CS.InvisibleBoss,'Start',nil)
  351.  
  352. xlua.hotfix(CS.Gun,'GoldChange',nil)
  353.  
  354. xlua.hotfix(CS.Gun,'DiamandsChange',nil)
  355.  
  356. xlua.hotfix(CS.CreateFish,'Update',nil)
  357.  
  358. xlua.hotfix(CS.Fish,'TakeDamage',nil)
  359.  
  360. xlua.hotfix(CS.Boss,'TakeDamage',nil)
  361.  
  362. xlua.hotfix(CS.Gun,'RotateGun',nil)
  363.  
  364. xlua.hotfix(CS.GunImage,'RotateGun',nil)
  365.  
  366. xlua.hotfix(CS.CreateFish,'Start',nil)
  367.  
  368. xlua.hotfix(CS.HotFixEmpty,'Start',nil)
  369.  
  370. xlua.hotfix(CS.HotFixEmpty,'Update',nil)
  371.  
  372. xlua.hotfix(CS.HotFixEmpty,'OnTriggerEnter',nil)
  373.  
  374. xlua.hotfix(CS.HotFixEmpty,'BehaviourMethod',nil)

Unity商业游戏底层资源加载框架(Unity2018.1)

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ResourceTest : MonoBehaviour
  6. {
  7. //public GameObject m_Prefab;
  8.  
  9. void Start() {
  10. //GameObject obj = GameObject.Instantiate(Resources.Load("Attack") as GameObject);
  11.  
  12. //AssetBundle assetBundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/attack");
  13. //GameObject obj = GameObject.Instantiate(assetBundle.LoadAsset<GameObject>("attack"));
  14.  
  15. GameObject obj = GameObject.Instantiate(UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>("Assets/GameData/Prefabs/Attack.prefab"));
  16. }
  17. }

常用四种加载方式

  1. TestSerialize
  2.  
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using System.Xml.Serialization;
  7.  
  8. [System.Serializable]
  9. public class TestSerialize {
  10.  
  11. [XmlAttribute("Id")]
  12. public int Id { get; set; }
  13.  
  14. [XmlAttribute("Name")]
  15. public string Name { get; set; }
  16.  
  17. [XmlElement("List")]
  18. public List<int> List { get; set; }
  19. }
  20.  
  21. AssetSerialize
  22.  
  23. using System.Collections;
  24. using System.Collections.Generic;
  25. using UnityEngine;
  26.  
  27. [CreateAssetMenu(fileName = "TestAssets", menuName = "CreateAssets", order = )]
  28. public class AssetSerialize : ScriptableObject {
  29. public int Id;
  30. public string Name;
  31. public List<string> TestList;
  32. }
  33.  
  34. ResourceTest
  35.  
  36. using System.Collections;
  37. using System.Collections.Generic;
  38. using UnityEngine;
  39. using System.IO;
  40. using System.Xml.Serialization;
  41. using System.Runtime.Serialization.Formatters.Binary;
  42.  
  43. public class ResourceTest : MonoBehaviour
  44. {
  45.  
  46. void Start() {
  47.  
  48. // SerializeTest();
  49. // DeSerializeTest();
  50. // BinarySerializeTest();
  51. //BinaryDeserializeTest();
  52. ReadTestAssets();
  53. }
  54.  
  55. void ReadTestAssets() {
  56. AssetSerialize assets = UnityEditor.AssetDatabase.LoadAssetAtPath<AssetSerialize>("Assets/Scripts/TestAssets.asset");
  57. Debug.Log(assets.Id);
  58. Debug.Log(assets.Name);
  59. foreach (string str in assets.TestList) {
  60. Debug.Log(str);
  61. }
  62. }
  63.  
  64. void SerializeTest() {
  65. TestSerialize testSerialize = new TestSerialize();
  66. testSerialize.Id = ;
  67. testSerialize.Name = "测试";
  68. testSerialize.List = new List<int>();
  69. testSerialize.List.Add();
  70. testSerialize.List.Add();
  71. XmlSerialize(testSerialize);
  72. }
  73.  
  74. void DeSerializeTest() {
  75. TestSerialize testSerialize = XmlDeSerialize();
  76. Debug.Log(testSerialize.Id + " " + testSerialize.Name);
  77. foreach (int a in testSerialize.List) {
  78. Debug.Log(a);
  79. }
  80. }
  81.  
  82. void XmlSerialize(TestSerialize testSerialize) {
  83. FileStream fileStream = new FileStream(Application.dataPath + "/test.xml", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
  84. StreamWriter sw = new StreamWriter(fileStream, System.Text.Encoding.UTF8);
  85. XmlSerializer xml = new XmlSerializer(testSerialize.GetType());
  86. xml.Serialize(sw, testSerialize);
  87. sw.Close();
  88. fileStream.Close();
  89. }
  90.  
  91. TestSerialize XmlDeSerialize() {
  92. FileStream fs = new FileStream(Application.dataPath + "/test.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
  93. XmlSerializer xs = new XmlSerializer(typeof(TestSerialize));
  94. TestSerialize testSerialize = (TestSerialize)xs.Deserialize(fs);
  95. fs.Close();
  96. return testSerialize;
  97. }
  98.  
  99. void BinarySerializeTest() {
  100. TestSerialize testSerialize = new TestSerialize();
  101. testSerialize.Id = ;
  102. testSerialize.Name = "二进制测试";
  103. testSerialize.List = new List<int>();
  104. testSerialize.List.Add();
  105. testSerialize.List.Add();
  106. BinarySerialize(testSerialize);
  107.  
  108. }
  109.  
  110. void BinaryDeserializeTest() {
  111. TestSerialize testSerialize = BinaryDeserialize();
  112. Debug.Log(testSerialize.Id + " " + testSerialize.Name);
  113. foreach (int a in testSerialize.List) {
  114. Debug.Log(a);
  115. }
  116. }
  117.  
  118. void BinarySerialize(TestSerialize serialize) {
  119. FileStream fs = new FileStream(Application.dataPath + "/test.bytes", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
  120. BinaryFormatter bf = new BinaryFormatter();
  121. bf.Serialize(fs, serialize);
  122. fs.Close();
  123. }
  124.  
  125. TestSerialize BinaryDeserialize() {
  126. TextAsset textAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/test.bytes");
  127. MemoryStream stream = new MemoryStream(textAsset.bytes);
  128. BinaryFormatter bf = new BinaryFormatter();
  129. TestSerialize testSerialize = (TestSerialize)bf.Deserialize(stream);
  130. stream.Close();
  131. return testSerialize;
  132. }
  133. }

序列化

Unity资源热更及代码热更(ILRuntime)

Unity 游戏框架搭建 2019 第一季 C# 核心知识与简易 Manager Of Managers 框架搭建 (已看)

Unity 游戏框架搭建 2019 第二季 模块/系统设计、命名、测试(资源管理/热更新)

游戏开发中的设计模式

相关文章

unity 打包AssetBundle

unity 热更新思路和实现

AssetBundle资源打包加载管理

http://tonytang1990.github.io/2018/10/24/AssetBundle%E8%B5%84%E6%BA%90%E6%89%93%E5%8C%85%E5%8A%A0%E8%BD%BD%E7%AE%A1%E7%90%86%E5%AD%A6%E4%B9%A0/?tdsourcetag=s_pctim_aiomsg

Unity S老师系列课程学习的更多相关文章

  1. solr课程学习系列-solr服务器配置(2)

    本文是solr课程学习系列的第2个课程,对solr基础知识不是很了解的请查看solr课程学习系列-solr的概念与结构(1) 本文以windows的solr6服务器搭建为例. 一.solr的工作环境: ...

  2. 公共语言运行库(CLR)开发系列课程(1):Pinvoke 简介 学习笔记

    前言 让拖管代码对象和非托管对象协同工作的过程称为互用性(Interoperability),通常简称为 Interop. P/Invoke在托管代码与非托管代码交互式时产生一个事务(Transiti ...

  3. 打通前后端全栈开发node+vue进阶【课程学习系统项目实战详细讲解】(3):用户添加/修改/删除 vue表格组件 vue分页组件

    第三章 建议学习时间8小时      总项目预计10章 学习方式:详细阅读,并手动实现相关代码(如果没有node和vue基础,请学习前面的vue和node基础博客[共10章] 演示地址:后台:demo ...

  4. 李宏毅老师机器学习课程笔记_ML Lecture 2: Where does the error come from?

    引言: 最近开始学习"机器学习",早就听说祖国宝岛的李宏毅老师的大名,一直没有时间看他的系列课程.今天听了一课,感觉非常棒,通俗易懂,而又能够抓住重点,中间还能加上一些很有趣的例子 ...

  5. 李宏毅老师机器学习课程笔记_ML Lecture 1: ML Lecture 1: Regression - Demo

    引言: 最近开始学习"机器学习",早就听说祖国宝岛的李宏毅老师的大名,一直没有时间看他的系列课程.今天听了一课,感觉非常棒,通俗易懂,而又能够抓住重点,中间还能加上一些很有趣的例子 ...

  6. 李宏毅老师机器学习课程笔记_ML Lecture 1: 回归案例研究

    引言: 最近开始学习"机器学习",早就听说祖国宝岛的李宏毅老师的大名,一直没有时间看他的系列课程.今天听了一课,感觉非常棒,通俗易懂,而又能够抓住重点,中间还能加上一些很有趣的例子 ...

  7. 李宏毅老师机器学习课程笔记_ML Lecture 0-2: Why we need to learn machine learning?

    引言: 最近开始学习"机器学习",早就听说祖国宝岛的李宏毅老师的大名,一直没有时间看他的系列课程.今天听了一课,感觉非常棒,通俗易懂,而又能够抓住重点,中间还能加上一些很有趣的例子 ...

  8. 李宏毅老师机器学习课程笔记_ML Lecture 0-1: Introduction of Machine Learning

    引言: 最近开始学习"机器学习",早就听说祖国宝岛的李宏毅老师的大名,一直没有时间看他的系列课程.今天听了一课,感觉非常棒,通俗易懂,而又能够抓住重点,中间还能加上一些很有趣的例子 ...

  9. C语言课程学习的总结

    C语言课程学习的总结 学习C程序这门课一年了,这是我们学的第一门专业课.在大学里,C语言不但是计算机专业的必修课程而且也是非计算机专业学习计算机基础的一门必修课程.所以作为我这个计算机专业的学生来说当 ...

随机推荐

  1. Python与用户交互

    目录 一.为什么交互? 二.如何交互? 三.Python2的交互 一.为什么交互?   让我们来回顾计算机的发明有何意义,计算机的发明是为了奴役计算机,解放劳动力.假设我们现在写了一个ATM系统取代了 ...

  2. 12-UA池和代理池

    一.UA池和代理池 1.UA池                                      scrapy的下载中间件: 下载中间件(Downloader Middlewares) 位于s ...

  3. Kafka生产消费API JAVA实现

    Maven依赖: <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka- ...

  4. Java日期时间API系列4-----Jdk7及以前的日期时间类的线程安全问题

    1.Date类为可变的,在多线程并发环境中会有线程安全问题. (1)可以使用锁来处理并发问题. (2)使用JDK8  Instant 或 LocalDateTime替代. 2.Calendar的子类为 ...

  5. YYLable 的使用 以及注意点

    NSString *title = @"不得不说 YYKit第三方框架确实很牛,YYLabel在富文本显示和操作方面相当强大,尤其是其异步渲染,让界面要多流畅有多流畅,这里我们介绍下简单的使 ...

  6. 配置flutter For IOS

    https://www.cnblogs.com/lovestarfish/p/10628205.html 第一步,下载flutter最新版,解压到自己的目录里: 提供网址:https://flutte ...

  7. gradle 参数配置监听

    说明 gradle提供了对project状态配置监听的接口回调,以方便我们来配置一些Project的配置属性,监听主要分为两大类,一种是通过project进行 回调,一种是通过gradle进行回调,作 ...

  8. EGit(Git Eclipse Plugin)使用

    https://shihlei.iteye.com/blog/2124411 前言: 1)Git于SVN的不同      Git是分布式数据库,本地创建仓库,即可在本地完成版本控制(等价于SVN在本地 ...

  9. 【原创】CentOS 7 安装解压版mysql5.7

    1.将mysql压缩包解压至 /usr/local 文件夹下,将其改名为mysql #解压 tar -zxf mysql-5.7.27-el7-x86_64.tar.gz -C /usr/local/ ...

  10. Troubleshooting ORA-1628 - max # extents (32765) reached for rollback segment <SEGMENT_NAME> (Doc ID 1580182.1)

    Troubleshooting ORA-1628 - max # extents (32765) reached for rollback segment <SEGMENT_NAME> ( ...