{
  "schemaVersion": "0.11.0",
  "canonical": "https://www.pystone.net/notes/unity-asset-memory-load-unload/",
  "atlas": "https://www.pystone.net/?node=unity-asset-memory-load-unload#knowledge-atlas",
  "markdown": "https://www.pystone.net/notes/unity-asset-memory-load-unload.md",
  "context": "https://www.pystone.net/notes/unity-asset-memory-load-unload.context.json",
  "knowledgeVersion": "224c990773de.5fa8af6e39fa",
  "build": {
    "siteCommit": "224c990773de166d23a886306577dd90379529ce",
    "notesCommit": "5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a",
    "builtAt": "1970-01-01T00:00:00.000Z",
    "version": "224c990773de.5fa8af6e39fa"
  },
  "id": "note:unity-asset-memory-load-unload",
  "slug": "unity-asset-memory-load-unload",
  "title": "资源与内存【加载、卸载、Destroy】",
  "type": "note",
  "visibility": "public",
  "idStability": "rename-stable",
  "author": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "publisher": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "aliases": [],
  "summary": "资源与内存【加载、卸载、Destroy】",
  "contentRole": "unspecified",
  "isMoc": false,
  "mocRecognition": "none",
  "generated": false,
  "attribution": "unspecified",
  "domain": "10-计算机、信息技术与工程",
  "tags": [],
  "mocs": [],
  "contentHash": "3fede94f325d5afac0c9a20659f55fb6a5edfcffcf72fc9eaea454c28b112a63",
  "assets": [
    {
      "reference": "assets/289969-20180402204239871-1854753914.png",
      "url": "/media/36fad32cb83092d272bd.png",
      "mediaType": "image/png",
      "contentHash": "36fad32cb83092d272bdb5fb1f937003eed0b730d3c19b7c1db0f5c1bef90754",
      "byteLength": 140974,
      "width": 500,
      "height": 473
    }
  ],
  "headings": [
    {
      "depth": 1,
      "text": "资源与内存【加载、卸载、Destroy】",
      "anchor": "资源与内存加载卸载destroy",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E8%B5%84%E6%BA%90%E4%B8%8E%E5%86%85%E5%AD%98%E5%8A%A0%E8%BD%BD%E5%8D%B8%E8%BD%BDdestroy"
    },
    {
      "depth": 2,
      "text": "Unity文件，文件引用，meta详解",
      "anchor": "unity文件文件引用meta详解",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#unity%E6%96%87%E4%BB%B6%E6%96%87%E4%BB%B6%E5%BC%95%E7%94%A8meta%E8%AF%A6%E8%A7%A3"
    },
    {
      "depth": 3,
      "text": "Assets目录下常见的文件类型",
      "anchor": "assets目录下常见的文件类型",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#assets%E7%9B%AE%E5%BD%95%E4%B8%8B%E5%B8%B8%E8%A7%81%E7%9A%84%E6%96%87%E4%BB%B6%E7%B1%BB%E5%9E%8B"
    },
    {
      "depth": 4,
      "text": "资源文件(ImportedAsset)",
      "anchor": "资源文件importedasset",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E8%B5%84%E6%BA%90%E6%96%87%E4%BB%B6importedasset"
    },
    {
      "depth": 4,
      "text": "代码文件",
      "anchor": "代码文件",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E4%BB%A3%E7%A0%81%E6%96%87%E4%BB%B6"
    },
    {
      "depth": 4,
      "text": "序列化文件(Native Asset)",
      "anchor": "序列化文件native-asset",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E5%BA%8F%E5%88%97%E5%8C%96%E6%96%87%E4%BB%B6native-asset"
    },
    {
      "depth": 4,
      "text": "文本文档",
      "anchor": "文本文档",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E6%96%87%E6%9C%AC%E6%96%87%E6%A1%A3"
    },
    {
      "depth": 4,
      "text": "非序列化文件",
      "anchor": "非序列化文件",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E9%9D%9E%E5%BA%8F%E5%88%97%E5%8C%96%E6%96%87%E4%BB%B6"
    },
    {
      "depth": 4,
      "text": "Meta文件",
      "anchor": "meta文件",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#meta%E6%96%87%E4%BB%B6"
    },
    {
      "depth": 3,
      "text": "Meta文件详解——Unity GUID/LocalID系统",
      "anchor": "meta文件详解unity-guidlocalid系统",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#meta%E6%96%87%E4%BB%B6%E8%AF%A6%E8%A7%A3unity-guidlocalid%E7%B3%BB%E7%BB%9F"
    },
    {
      "depth": 4,
      "text": "GUID",
      "anchor": "guid",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#guid"
    },
    {
      "depth": 4,
      "text": "ImportSetting数据",
      "anchor": "importsetting数据",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#importsetting%E6%95%B0%E6%8D%AE"
    },
    {
      "depth": 4,
      "text": "FileID（LocalID）",
      "anchor": "fileidlocalid",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#fileidlocalid"
    },
    {
      "depth": 3,
      "text": "序列化文件详解——Unity文件引用系统",
      "anchor": "序列化文件详解unity文件引用系统",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E5%BA%8F%E5%88%97%E5%8C%96%E6%96%87%E4%BB%B6%E8%AF%A6%E8%A7%A3unity%E6%96%87%E4%BB%B6%E5%BC%95%E7%94%A8%E7%B3%BB%E7%BB%9F"
    },
    {
      "depth": 4,
      "text": "GameObject数据",
      "anchor": "gameobject数据",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#gameobject%E6%95%B0%E6%8D%AE"
    },
    {
      "depth": 4,
      "text": "组件数据",
      "anchor": "组件数据",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E7%BB%84%E4%BB%B6%E6%95%B0%E6%8D%AE"
    },
    {
      "depth": 4,
      "text": "Prefab数据",
      "anchor": "prefab数据",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#prefab%E6%95%B0%E6%8D%AE"
    },
    {
      "depth": 2,
      "text": "资源导入",
      "anchor": "资源导入",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E8%B5%84%E6%BA%90%E5%AF%BC%E5%85%A5"
    },
    {
      "depth": 3,
      "text": "What happens when Unity imports an Asset?",
      "anchor": "what-happens-when-unity-imports-an-asset",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#what-happens-when-unity-imports-an-asset"
    },
    {
      "depth": 3,
      "text": "The import settings can alter the processing of the asset",
      "anchor": "the-import-settings-can-alter-the-processing-of-the-asset",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#the-import-settings-can-alter-the-processing-of-the-asset"
    },
    {
      "depth": 2,
      "text": "AssetDatabase",
      "anchor": "assetdatabase",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#assetdatabase"
    },
    {
      "depth": 3,
      "text": "Importing an Asset",
      "anchor": "importing-an-asset",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#importing-an-asset"
    },
    {
      "depth": 3,
      "text": "Loading an Asset",
      "anchor": "loading-an-asset",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#loading-an-asset"
    },
    {
      "depth": 3,
      "text": "File Operations using the AssetDatabase",
      "anchor": "file-operations-using-the-assetdatabase",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#file-operations-using-the-assetdatabase"
    },
    {
      "depth": 3,
      "text": "Using AssetDatabase.Refresh",
      "anchor": "using-assetdatabaserefresh",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#using-assetdatabaserefresh"
    },
    {
      "depth": 3,
      "text": "CreateAssets & FindAssets & ScriptableObject",
      "anchor": "createassets-findassets-scriptableobject",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#createassets-findassets-scriptableobject"
    },
    {
      "depth": 2,
      "text": "AssetBundle",
      "anchor": "assetbundle",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#assetbundle"
    },
    {
      "depth": 2,
      "text": "资源卸载（Unload & Destroy）",
      "anchor": "资源卸载unload-destroy",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E8%B5%84%E6%BA%90%E5%8D%B8%E8%BD%BDunload-destroy"
    },
    {
      "depth": 3,
      "text": "Destroy",
      "anchor": "destroy",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#destroy"
    },
    {
      "depth": 4,
      "text": "概述",
      "anchor": "概述",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E6%A6%82%E8%BF%B0"
    },
    {
      "depth": 4,
      "text": "注意点",
      "anchor": "注意点",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E6%B3%A8%E6%84%8F%E7%82%B9"
    },
    {
      "depth": 4,
      "text": "作用对象",
      "anchor": "作用对象",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E4%BD%9C%E7%94%A8%E5%AF%B9%E8%B1%A1"
    },
    {
      "depth": 4,
      "text": "测试",
      "anchor": "测试",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E6%B5%8B%E8%AF%95"
    },
    {
      "depth": 3,
      "text": "Unload",
      "anchor": "unload",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#unload"
    },
    {
      "depth": 4,
      "text": "Resources.UnloadUnusedAssets",
      "anchor": "resourcesunloadunusedassets",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#resourcesunloadunusedassets"
    },
    {
      "depth": 4,
      "text": "Resources.UnloadAsset()",
      "anchor": "resourcesunloadasset",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#resourcesunloadasset"
    },
    {
      "depth": 4,
      "text": "EditorUtility.UnloadUnusedAssets",
      "anchor": "editorutilityunloadunusedassets",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#editorutilityunloadunusedassets"
    },
    {
      "depth": 2,
      "text": "资源卸载与内存管理问题的处理经验",
      "anchor": "资源卸载与内存管理问题的处理经验",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#%E8%B5%84%E6%BA%90%E5%8D%B8%E8%BD%BD%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E9%97%AE%E9%A2%98%E7%9A%84%E5%A4%84%E7%90%86%E7%BB%8F%E9%AA%8C"
    },
    {
      "depth": 2,
      "text": "Ref",
      "anchor": "ref",
      "citation": "https://www.pystone.net/notes/unity-asset-memory-load-unload/#ref"
    }
  ],
  "claims": [],
  "outgoing": [],
  "incoming": [
    {
      "id": "note:game-graphics-and-runtime",
      "title": "游戏图形与运行时",
      "url": "https://www.pystone.net/notes/game-graphics-and-runtime/",
      "atlas": "https://www.pystone.net/?node=game-graphics-and-runtime#knowledge-atlas",
      "label": "游戏图形与运行时",
      "origin": "explicit",
      "humanReviewed": true,
      "context": "Unity中的“资源与内存【加载、卸载、Destroy】”导航项",
      "citation": "https://www.pystone.net/notes/game-graphics-and-runtime/#unity"
    }
  ],
  "contentMarkdown": "# 资源与内存【加载、卸载、Destroy】\n\n> 创建时间：2020/4/28 11:31\n\n  * 资源与内存【加载、卸载、Destroy】\n    * Unity文件，文件引用，meta详解\n      * Assets目录下常见的文件类型\n        * 资源文件(ImportedAsset)\n        * 代码文件\n        * 序列化文件(Native Asset)\n        * 文本文档\n        * 非序列化文件\n        * Meta文件\n      * Meta文件详解——Unity GUID/LocalID系统\n        * GUID\n        * ImportSetting数据\n        * FileID（LocalID）\n      * 序列化文件详解——Unity文件引用系统\n        * GameObject数据\n        * 组件数据\n        * Prefab数据\n    * 资源导入\n      * What happens when Unity imports an Asset?\n      * The import settings can alter the processing of the asset\n    * AssetDatabase\n      * Importing an Asset\n      * Loading an Asset\n      * File Operations using the AssetDatabase\n      * Using AssetDatabase.Refresh\n      * CreateAssets & FindAssets & ScriptableObject\n    * AssetBundle\n    * 资源卸载（Unload & Destroy）\n      * Destroy\n        * 概述\n        * 注意点\n        * 作用对象\n        * 测试\n      * Unload\n        * Resources.UnloadUnusedAssets\n        * Resources.UnloadAsset()\n        * EditorUtility.UnloadUnusedAssets\n    * 资源卸载与内存管理问题的处理经验\n    * Ref\n\n## Unity文件，文件引用，meta详解\n\n### Assets目录下常见的文件类型\n\n#### 资源文件(ImportedAsset)\n\n创建好的，并且不再修改的文件：FBX文件，贴图文件，音频文件，视频文件，动画文件\n导入时进行转化，每一个类型都对应一个AssetImporter\n点击这样的资源，在Inspector面板会出现设置界面\n\n#### 代码文件\n\n代码文件包括所有的代码文件，代码库文件，shader文件等，在导入时，unity会进行一次编译。\n\n#### 序列化文件(Native Asset)\n\n序列化文件通常是指unity能够序列化的文件，一般是unity自身的一些类型。比如prefab(预制体)，unity3d(场景)文件，asset(ScriptableObject)文件.mat文件(材质球)，这些文件能够在运行时直接反序列化为对应类的一个实例。\n\n#### 文本文档\n\n不是序列化文件，但是unity可以识别为TextAsset。\n很像资源文件，但是又不需要资源文件那样进行设置和转化。\n如txt、xml文件等等\n\n#### 非序列化文件\n\n非序列文件是Unity无法识别的文件，比如文件夹\n\n#### Meta文件\n\nmeta文件在unity中的作用非常关键，它有2个作用\n\n  * 定义在它同目录下，同名的非meta文件的唯一ID：GUID。而对于unity的序列化文件来说，引用的对象用的就是这个GUID。所以一旦meta中的GUID变更了，就要注意，它很可能引起一场引用丢失的灾难\n\n  * 存储资源文件的ImportSetting数据。在上文中资源文件是有ImportSetting数据的，这个数据正数存储在meta文件中。ImportSetting中专门有存储Assetbundle相关的数据。这些数据帮助编辑器去搜集所有需要打包的文件并分门别类。所以每一次修改配置都会修改meta文件。\n\n### Meta文件详解——Unity GUID/LocalID系统\n\nmeta文件——文本文档，YAML格式写的（序列化文件都是用这个格式写）\n\n#### GUID\n\nguid代表该文件，无论什么类型（甚至是文件夹）。\n通过GUID就可以找到工程中的这个文件，无论它在项目的什么位置。\n在编辑器中使用AssetDatabase.GUIDToAssetPath和AssetDatabase.AssetPathToGUID进行互转。\n\n#### ImportSetting数据\n\n根据不同的文件类型，它的数据是不同的ImportSetting数据（Inspector面板设置），比如上面的NativeFormatImporter，ModelImporter，AudioImporter等等。把一个文件和这个文件的meta文件从一个Unity工程复制到另一个Unity工程中，它的配置是不会变的。（将fbx和它的meta文件拷贝到另一个工程，不需要重新裁剪动画）\n\n#### FileID（LocalID）\n\n如果是一个图集，下面有若干个图片，那么就需要另外一个ID来表示，这就是LocalID（meta文件名为: FileID。）\n\n  * 对于资源文件，非序列化文件，由于一般不会去更改源文件，所以FileID存储在meta文件中。\n\n  * 对于序列化文件，自身数据里面会存储自身的FileID，也会记录所有子文件的FileID\n\n> 所以在每次svn提交时如果发现有meta文件变更，一定要打开看一下。看看这个guid是否被更改。理论上是不需要更改的。\n\n### 序列化文件详解——Unity文件引用系统\n\n用sublime打开一个Scene文件(.unity)，\n大概的数据：\n\n  * OcclusionCullingSettings裁剪数据（菜单Window->Occlusion面板中的数据）\n\n  * RenderSettings（菜单Window->Lighting->Settings面板中的部分数据）\n\n  * LightmapSettings（菜单Window->Lighting->Settings面板中的其他部分数据）\n\n  * NavMeshSettings（菜单Window->Navigation面板中的数据）\n\n  * 之后就是场景中的GameObject的数据\n\n#### GameObject数据\n\nName就是Main Camera\n某个物体上有4个组件，每个组件有一个FileID，然后在需要引用时，使用这些FileID即可。实例化一个这样的GameObject时，只要依照次序，依次创建物体，组件，初始化数据并进行引用绑定即可在场景中生成一个实例。\n\n> 在Inspector面板中的右上角点击，然后选择Debug转成Debug模式下的Inspector面板。\n>  在Hierarchy面板中选中Main Camera可以看到如图所示，所有的组件的LocalIdentfierInFile的值就是刚刚在Sublime中看到的数据\n\n  * **InstanceID** 是unity中一个实例的ID。\n\n  * 每一个Unity实例都会有一个InstanceID。在运行时，用UnityEngine.Object的GetInstanceID获取（《Unity编辑器下和运行时的加载过程》）\n\n#### 组件数据\n\n在GameObject之后就是组件数据。可以结合Unity中这个组件的面板来了解每一个数据的意义。\n\n> 组件FlareLayer，在YAML里面只是一个Behaviour（所有Behaviour组件都看不到类型名字），怎么样才能知道他是一个FlareLayer？\n>  FileID左边我们看到一个124。每一个unity类型都有一个对应的数字。\n>  参考：<https://docs.unity3d.com/Manual/ClassIDReference.html>\n\n任何一个文件都可以通过GUID找到，然后通过FileID找到它内部的子文件。所以这样就能识别出这个具体是什么类了。\n\n#### Prefab数据\n\n在YAML的最下面有一个数据是Prefab数据，保存了最重要的几个数据：\nModification：每个组件的修改数据列表，但凡修改的数据，都会在这里体现。记录了：哪个资源（GUID）的哪个组件(FileID)的哪个成员(PropertyPath)的值(value)发生了改变。\nParentPrefab：表示是哪一个Prefab。\n\n![Alt text](assets/289969-20180402204239871-1854753914.png)\n\n## 资源导入\n\nUnity automatically imports assets and manages various kinds of additional data about them for you, such as what import settings should be used to import the asset, and where the asset is used throughout your project.\n\n### What happens when Unity imports an Asset?\n\n  1. A Unique ID is assigned\nThis ID is used internally by Unity to refer to the asset which means the asset can be moved or renamed without references to the asset breaking.\n\n> the editor frequently checks the contents of the Assets folder against the list of assets it already knows about.\n\n  2. A .meta file is created\n\n> If an asset loses its meta file (for example, if you moved or renamed the asset outside of Unity, without moving/renaming the corresponding .meta file), any reference to that asset will be broken. Unity would generate a new .meta file for the moved/renamed asset as if it were a brand new asset, and delete the old “orphaned” .meta file.\n\n  3. The source asset is processed\nUnity reads and processes any files that you add to the Assets folder, converting the contents of the file to internal game-ready versions of the data. The actual asset files remain unmodified, and the processed and converted versions of the data are stored in the project’s **Library** folder.\n\n> the Photoshop file format is convenient to work with and can be saved directly into your Assets folder, but hardware such as mobile devices and PC graphics cards can’t accept that format directly to render as textures. All the data for Unity’s internal representation of your assets is stored in the Library folder which can be thought of as similar to a cache folder. As a user, you should never have to alter the Library folder manually and attempting to do so may affect the functioning of the project in the Unity editor. However, it is always safe to delete the Library folder (while the project is not open in Unity) as all its data is generated from what is stored in the Assets and ProjectSettings folders. This also means that the Library folder should not be included in version control.\n>\n> Sometimes multiple assets are created from an import\n>\n>   * A 3D file, such as an FBX, defines Materials and/or contains embedded Textures.\n>\n>   * An image file imported as multiple sprites.\n>\n>   * A 3D file contains multiple animation timelines, or has multiple separate clips defined within its animation import settings.\n>\n>\n\n### The import settings can alter the processing of the asset\n\nAs well as the unique ID assigned to the asset, the meta files contain values for all the import settings you see in the inspector when you have an asset selected in your project window. For a texture, this includes settings such as the Texture Type, Wrap Mode, Filter Mode and Aniso Level.\n\nIf you change the import settings for an asset, those changed settings are stored in the .meta file accompanying the asset. The asset will be re-imported according to your new settings, and the corresponding imported “game-ready” data will be updated in the project’s Library folder.\n\n## AssetDatabase\n\nAssetDatabase is an API which allows you to access the assets contained in your project. Among other things, it provides methods to find and load assets and also to create, delete and modify them. The Unity Editor uses the AssetDatabase internally to keep track of asset files and maintain the linkage between assets and objects that reference them.\n\n### Importing an Asset\n\n### Loading an Asset\n\n### File Operations using the AssetDatabase\n\n### Using AssetDatabase.Refresh\n\nWhen you have finished modifying assets, you should call AssetDatabase.Refresh to commit your changes to the database and make them visible in the project.\n\n### CreateAssets & FindAssets & ScriptableObject\n\n  1. 对于ScriptableObject，使用CreateInstance来创建Asset实例对象\n`testI = (ScriptObj)ScriptableObject.CreateInstance(typeof(ScriptObj));`\n\n  2. 对于其他资源类型，使用new来创建对象\n\n  3. 然后调用 `AssetDatabase.CreateAsset`函数，将实例对象作为资源存储在Assets路径当中。\n\n  4. 最后使用`AssetDatabase.FindAssets`获取相应资源的GUID\n\n  5. 由 `AssetDatabase.GUIDToAssetPath` 获取相应资源的路径。\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n## AssetBundle\n\n<https://blog.csdn.net/qq_35361471/article/details/82854560>\n\n## 资源卸载（Unload & Destroy）\n\n### Destroy\n\n#### 概述\n\nUNITY Destroy()和DestroyImadiate()都不会立即释放对象内存\nDestroyImadiate是立即将物体从场景hierachy中移除，并标记为 “null”，注意 是带引号的null。这是UNITY内部的一个处理技巧。关于这个技巧有很争议。\nDestroy要等到帧末才会将物体从场景层级中移除并标记为”null”。\n\n不管如何，二者都只是UNITY引擎层面的标记与处理，但在.NET底层，对象的内存都没有释放，只有手动GC.Collect()或等待NET去GC时才会释放掉对象内存。\n如果该对象在其他地方还有引用的话，GC也无法将对象的内存释放。\n\n#### 注意点\n\n（1）obj并不会立即销毁，而是需要等待下一个Update更新，所以还是可以被print出来；\n（2）DestroyImmediate立即对对像进行销毁，print出来是null；\n（3）Destroy销毁场景中的物体，但内存中还存在，当令它需要销毁时，只是给一个标识。而内存中它依然是存在的，只有当内存不够，或一段时间没有再次被引用时（或者更多合理的条件满足），机制才会将它销毁并释放内存；\n（4）这样做的目的就是为了避免频繁对内存的读写操作。回收器会定时清理一次内存中引用计数为0的对象，很可能你的要销毁的对象在其他地方还有引用而你自己不清楚，直接销毁可能导致其他地方空引用错误；\n（5）建议使用平常Destroy函数，而不是DestroyImmediate函数；\n\n#### 作用对象\n\nGameObject、Component这样的在内存当中的实例，可以直接销毁，销毁掉后对硬盘上的资源是没有影响的。\nLoad进来的资源文件（Texture等）不可以使用DestroyImmediate(obj)直接销毁。如果使用DestroyImmediate(obj, true)接口，可以销毁。对于序列化文件等Unity可以直接识别和接管的文件，相应的资源文件会销毁掉，而对于Texture这样的资源，Unity无法识别资源原始的图片，只能识别导入后加入Library中的文件，则会销毁Library中相应的资源，并断掉对该资源的引用（路径上就找不到该资源了）。而对于图片，由于原始文件没有被销毁，重新打开项目后，该图片会重新被Import进来。\n\n总之，Destroy接口本身是不应该用来销毁资源的。\n\n如果在游戏当中把资源Destroy掉，下次打开游戏，这个资源就没有了，加载不到了。\n\n#### 测试\n\n测试代码如下：点ADD按钮不断创建对象，点DEL按钮清除所有对象，通过观察进程内存数值来察看对象内存是否释放。\n\n```csharp\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic dyn = 1;\n        object obj = 1;\n        dyn = dyn + 3;\n        //obj = obj + 3; 报错\n\n        // Rest the mouse pointer over dyn and obj to see their\n        // types at compile time.\n        System.Console.WriteLine(dyn.GetType());\n        System.Console.WriteLine(obj.GetType());\n    }\n}\n\n```\n\n### Unload\n\n#### Resources.UnloadUnusedAssets\n\n运行中卸载，可能是在帧末尾卸载\n\n#### Resources.UnloadAsset()\n\n对于场景当中的特定资源，如果相机照射到他或者在脚本中有对资源的引用的话就无法卸载。\n如果相机没有看到他，并且没有被引用到，那么该资源会在内存当中被卸载。而若下次引用到他，或者相机照射到他，那么该资源会被重新加载到内存当中。\n\n#### EditorUtility.UnloadUnusedAssets\n\n编辑器下的卸载资源接口。\n\n## 资源卸载与内存管理问题的处理经验\n\n  1. Editor中的脚本对物体的引用无法用Memory Profiler检测到，因为Editor脚本对MemoryProfiler是不可见的。\n\n  2. 只要脚本中有对Texture等资源实例的引用，那么相应的资源就无法卸载掉。\n\n  3. EditorUtility.UnloadUnusedAssets确实可以卸载没有被引用的资源对象，但是不会一调用就立即卸载掉，可能稍等一会儿才会卸载掉。所以，在这个函数调用过后立即检测内存，是看不出来卸载的效果的，过一小段时间后，再打印内存，就可以看到卸载的效果。根据对内存的监控可以判断：刚刚调用Unload资源函数的时候，内存不会立即释放，在下次加载资源的时候，会进行内存释放操作。\n\n  4. 把加载进内存的对象直接Destroy掉，就不会占用内存，不需要调用Unload函数也可以。 如果把对资源的引用设置为null，不调用unload函数的话，资源会留在内存当中，只有调用unload之后，资源才会被卸载\n\n## Ref\n\n<https://www.cnblogs.com/CodeGize/p/8697227.html>\n<https://www.cnblogs.com/timeObjserver/p/7575035.html>\n<https://docs.unity3d.com/2017.2/Documentation/Manual/BehindtheScenes.html>\n"
}
