unity为我们提供了自定义资源导入的流程,通过该流程,我们可以
- 对导入的资源进行检查,及预处理,比如检查贴图是否是2的n次幂,设置贴图参数,创建预制等
- 对unity无法识别的资源,加入导入流程
方法:派生 ScriptedImporter,并实现 OnImportAsset() 方法。
例子
using UnityEngine;
using UnityEditor;
using UnityEditor.Experimental.AssetImporters;
using System.IO;
/// <summary>
/// 识别并导入后缀是.custom的文件资源,这里我们的测试资源是个txt文本文件,存储了一个 Json 格式的 Vector3 数据
/// </summary>
[ScriptedImporter(1, "custom")]
public class CustomAssetType : ScriptedImporter
{
public override void OnImportAsset(AssetImportContext ctx)
{
// 创建立方体
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
// 从资源文件读取位置
var pos = JsonUtility.FromJson<Vector3>(File.ReadAllText(ctx.assetPath));
cube.transform.position = pos;
cube.transform.localScale = Vector3.one;
// 将立方体绑定到对象上
ctx.AddObjectToAsset("obj", cube);
ctx.SetMainObject(cube);
// 添加材质
Material mtl = new Material(Shader.Find("Standard"));
mtl.color = Color.red;
ctx.AddObjectToAsset("material", mtl);
}
}