objectToAdd | 要添加到现有资源的对象。 |
path | 目标资源的文件系统路径。 |
将objectToAdd
添加到path
处的现有资源。
请注意,您应该只将对象添加到“.asset”资源中,例如导入的模型或纹理对象将丢失其数据。
所有路径相对于项目文件夹。
注意:您不能添加游戏对象;请改用PrefabUtility。
using UnityEngine; using UnityEditor;
public class AddObjectToAssetPathExample { [MenuItem("AssetDatabase/AddObjectToAssetPathExample")] static void AddObjectToPathExample() { // Create a simple material object Material material = new Material(Shader.Find("Specular")); material.name = "My material";
// Create an instance of a simple scriptable object DummyObject dummyObject = ScriptableObject.CreateInstance<DummyObject>(); dummyObject.name = "My scriptable asset";
// Create the scriptable object asset AssetDatabase.CreateAsset(dummyObject, "Assets/dummyObject.asset");
// Get the path of the scriptable object asset string dummyObjectPath = AssetDatabase.GetAssetPath(dummyObject);
// Add the material to the scriptable object asset AssetDatabase.AddObjectToAsset(material, dummyObjectPath);
// Serializing the changes in memory to disk AssetDatabase.SaveAssets();
// Print the path of the created asset Debug.Log(AssetDatabase.GetAssetPath(dummyObject)); } }
// The DummyObject class used in the example above public class DummyObject : ScriptableObject { public string objectName = "dummy"; }
objectToAdd | 要添加到现有资源的对象。 |
assetObject | 目标资源。 |
将objectToAdd
添加到由assetObject
标识的现有资源。
注意:在调用 AddObjectToAsset 之前,如果objectToAdd
已存在于磁盘上,将会生成错误(例如,尝试将“MyMaterial”添加到现有资源):“由于材质'MyMaterial'已经是'Assets/MyMaterial.mat'处的资源,因此无法将其添加到资源文件中!”
注意:您必须将内存中的更改序列化到磁盘。
这是因为必须将内存中修改过的资源保存到磁盘。
如果未执行此操作,将会产生不一致的结果警告,因为对资源的内存修改将会丢失。
using UnityEngine; using UnityEditor;
public class AddObjectToAssetExample { [MenuItem("AssetDatabase/AddObjectExample")] static void AddObjectExample() { // Create a simple material object Material material = new Material(Shader.Find("Specular")); material.name = "My material";
// Create an instance of a simple scriptable object DummyObject dummyObject = ScriptableObject.CreateInstance<DummyObject>(); dummyObject.name = "My scriptable asset";
// Create the scriptable object asset AssetDatabase.CreateAsset(dummyObject, "Assets/dummyObject.asset");
// Add the material to the scriptable object asset AssetDatabase.AddObjectToAsset(material, dummyObject);
// Serializing the changes in memory to disk AssetDatabase.SaveAssets();
// Print the path of the created asset Debug.Log(AssetDatabase.GetAssetPath(dummyObject)); } }
// The DummyObject class used in the example above public class DummyObject : ScriptableObject { public string objectName = "dummy"; }