ctx | 此参数包含处理导入事件所需的所有上下文信息,同时也由自定义导入器来存储生成的 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 a GameObject and will be automatically converted into a Prefab // (Only the 'Main Asset' is elligible to become a Prefab.) ctx.AddObjectToAsset("main obj", cube); ctx.SetMainObject(cube);
var material = new Material(Shader.Find("Standard")); ctx.DependsOnCustomDependency("StandardShaderDependencyHash");
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); } }
如需在以上示例中使用 Shader.Find() 函数,您需要编写自定义依赖项(用于查找您要找到的着色器)并定期对其进行更新。此操作可防止 Shader.Find() 函数绕过其他依赖性检查方法。以下代码是一个示例,演示如何编写此用途的自定义依赖项。
using UnityEditor; using UnityEngine;
static class ShaderDependencyUpdater { [InitializeOnLoadMethod] static void ShaderDependencyInit() { EditorApplication.update += ShaderDependencyUpdate; } static void ShaderDependencyUpdate() { var shader = Shader.Find("Standard"); AssetDatabase.TryGetGUIDAndLocalFileIdentifier(shader, out var guid, out long id); var hash = new Hash128(); hash.Append(guid); hash.Append(id); AssetDatabase.RegisterCustomDependency("StandardShaderDependencyHash", hash); } }