Version: 2022.1

AssetDatabase.ForceReserializeAssets

切换到手册
public static void ForceReserializeAssets ();
public static void ForceReserializeAssets (IEnumerable<string> assetPaths, ForceReserializeAssetsOptions options);

参数

assetPaths The paths to the assets that should be reserialized.
options 指定是重新序列化资源本身,还是它们的 .meta 文件,亦或者是重新序列化这两者。如果省略该属性,则默认重新序列化这两者。

描述

强制加载给定资源并将其重新序列化,这样会将所有待定数据更改都刷新到磁盘。

当 Unity 加载来自资源或场景文件的旧数据时,数据会在内存中动态升级,但不会写回到磁盘,除非用户执行显式污染对象的操作(例如:改变对象的值)。该方法允许您将任何资源或者场景文件预先加载、升级并写回到磁盘,不需要手动污染它们。

Unity 的常规行为有许多优势,尤其适用于带有版本控制系统的项目,此类项目迁移到一个新的 Unity 版本后,会主动升级所有资源,这会导致提交大量更改的文件列表。然而缺点是,当用户继续处理项目时,升级内容会与刻意更改的内容混合在一起。借助该方法,您能够以一种可控方式主动准确地确定要升级的资源以及升级时间。

Note: You should only call this method from direct user actions, such as a menu item. You should not call ForceReserializeAssets from a Unity callback (such as OnEnable), because it might be called while a scene is being modified. If you do this, Unity throws an exception.

using UnityEditor;
using UnityEngine;

public class AssetDatabaseExamples : MonoBehaviour { [MenuItem("AssetDatabase/Force Reserialize Assets Example")] static void UpdateGroundMaterials() { for (var i = 0; i < 10; i++) { var matPath = $"Assets/Materials/GroundMaterial{i}.mat"; var mat = (Material)AssetDatabase.LoadMainAssetAtPath(matPath); AssetImporter.GetAtPath(matPath).SetAssetBundleNameAndVariant("GroundBundle", ""); mat.shader = Shader.Find("Standard"); mat.color = Color.white; mat.mainTexture = (Texture)AssetDatabase.LoadMainAssetAtPath($"Assets/Textures/GroundTexture{i}.jpg"); } AssetDatabase.ForceReserializeAssets();

} }