Scripted Importer は Unity スクリプティング API の一部です。Scripted Importer を使用すると C# でカスタムアセットインポーターを作成できます。これにより、Unity でネイティブにサポートされていないファイル形式の独自のサポートを追加できます。
カスタムインポーターを作成するには、抽象クラス ScriptedImporter を特殊化し、ScriptedImporter 属性を適用します。これにより、カスタムインポーターが登録され、1 つ以上のファイル拡張子が処理されます。登録されたファイル拡張子に一致する新規または変更されたファイルが Asset パイプラインによって検出されると、Unity はカスタムインポーターのメソッド OnImportAsset を呼び出します。
注意:Scripted Importer は、すでに Unity によってネイティブに処理されているファイル拡張子は処理できません。
以下に示すのは、Scripted Importer の簡単な例です。拡張子が “cube” のアセットファイルを、メインアセットのキューブプリミティブと、デフォルトのマテリアルおよびカラーとともに Unity プレハブにインポートし、アセットファイルから読み込んだその位置を割り当てます。
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 属性を配置することによって、インポーターは Unity のアセットパイプラインに登録されます。ScriptedImporter の基本クラスを実装します。OnImportAsset の ctx 引数には、インポートイベントの入力データと出力データの両方が含まれます。SetMainAsset への呼び出しを 1 回 (1 回のみ) 発生させる必要があります。AddSubAsset の呼び出しを生成できます。また、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 インポータープラグインは Scripted Importer を使用するように更新されています。詳細については、Unity GitHub: AlembicImporter を参照してください。
USD: USD インポータープラグインは、Scripted Importer を使用します。詳細については、USD Importer パッケージのドキュメントを参照してください。