Scripted Importers are part of the Unity Scripting API. You can use Scripted Importers to write custom Asset importers in C#, which allows you to add your own support for file formats that are not natively supported by Unity.
You can create a custom importer by specializing the abstract class ScriptedImporter and applying the ScriptedImporter attribute. This registers your custom importer to handle one or more file extensions. When a file matching the registered file extensions is detected by the Asset pipeline as being new or changed, Unity invokes the method OnImportAsset
of your custom importer.
注意:Scripted Importer 无法处理已由 Unity 本身处理的文件扩展名。
Below is a simple example as Scripted Importer: It imports asset files with the extension “cube” into a Unity Prefab with a cube primitive as the main Asset and a default material and color, and assigns its position from a value read from the Asset file:
using UnityEngine;
using UnityEditor.AssetImporters;
using System.IO;
[ScriptedImporter(1, "cube")]
public class CubeImporter : ScriptedImporter
{
public float m_Scale = 1;
public override void OnImportAsset(AssetImportContext ctx)
{
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
var position = JsonUtility.FromJson<Vector3>(File.ReadAllText(ctx.assetPath));
cube.transform.position = position;
cube.transform.localScale = new Vector3(m_Scale, m_Scale, m_Scale);
// 'cube' is a GameObject and will be automatically converted into a prefab
// (Only the 'Main Asset' is eligible to become a Prefab.)
ctx.AddObjectToAsset("main obj", cube);
ctx.SetMainObject(cube);
var material = new Material(Shader.Find("Standard"));
material.color = Color.red;
// Assets must be assigned a unique identifier string consistent across imports
ctx.AddObjectToAsset("my Material", material);
// Assets that are not passed into the context as import outputs must be destroyed
var tempMesh = new Mesh();
DestroyImmediate(tempMesh);
}
}
注意:
ScriptedImporter
属性。ScriptedImporter
基类。OnImportAsset
的 ctx 参数包含导入事件的输入和输出数据。SetMainAsset
的一次(且仅一次)调用。AddSubAsset
的任意次调用。您还可以实现自定义的 Import Settings Editor,为此需要专门定义 ScriptedImporterEditor 类,并使用 CustomEditor
类属性对其进行修饰以告知其用于哪种类型的导入器。
例如:
using UnityEditor;
using UnityEditor.AssetImporters;
using UnityEditor.SceneManagement;
using UnityEngine;
[CustomEditor(typeof(CubeImporter))]
public class CubeImporterEditor: ScriptedImporterEditor
{
public override void OnInspectorGUI()
{
var colorShift = new GUIContent("Color Shift");
var prop = serializedObject.FindProperty("m_ColorShift");
EditorGUILayout.PropertyField(prop, colorShift);
base.ApplyRevertGUI();
}
}
将 Scripted Importer 类添加到项目后,可以像使用 Unity 支持的任何其他本机文件类型一样使用它:
__Alembic__:Alembic Importer 插件已更新为使用 Scripted Importer。有关更多信息,请访问 Unity github:AlembicImporter。
__USD__:USD Importer 插件已更新为使用 Scripted Importer。 有关更多信息,请访问 Unity github:USDForUnity。