Редактор по умолчанию для всех настроек импортера объектов.
Используйте редактор по умолчанию, чтобы изменить настройки импорта ресурсов. Вы можете определить пользовательский редактор настроек импорта для определенного типа активов. Для этого создайте новый класс, наследуемый от AssetImporterEditor и использующий CustomEditorAttribute, ссылающийся на ScriptedImporter.
В следующем примере показано, как создать пользовательский редактор ScriptedImporterEditor для ScriptedImporter с пользовательским макетом.
using System.IO;
using UnityEditor;
using UnityEditor.AssetImporters;
using UnityEngine;
[CustomEditor(typeof(TransformImporter))]
[CanEditMultipleObjects]
public class TransformImporterEditor : ScriptedImporterEditor
{
// Stored SerializedProperty to draw in OnInspectorGUI.
SerializedProperty m_GenerateChild;
public override void OnEnable()
{
base.OnEnable();
// Once in OnEnable, retrieve the serializedObject property and store it.
m_GenerateChild = serializedObject.FindProperty("generateChild");
}
public override void OnInspectorGUI()
{
// Update the serializedObject in case it has been changed outside the Inspector.
serializedObject.Update();
// Draw the boolean property.
EditorGUILayout.PropertyField(m_GenerateChild);
// Apply the changes so Undo/Redo is working
serializedObject.ApplyModifiedProperties();
// Call ApplyRevertGUI to show Apply and Revert buttons.
ApplyRevertGUI();
}
}
[ScriptedImporter(0, ".transform")]
public class TransformImporter : ScriptedImporter
{
public bool generateChild;
public override void OnImportAsset(AssetImportContext ctx)
{
GameObject root = ObjectFactory.CreateGameObject(Path.GetFileNameWithoutExtension(ctx.assetPath));
if (generateChild)
{
GameObject child = ObjectFactory.CreateGameObject("child");
child.transform.SetParent(root.transform);
}
ctx.AddObjectToAsset("main", root);
ctx.SetMainObject(root);
}
}
В следующем примере показан конкретный случай, когда пользователь не может изменить настройки, а кнопки "Применить/Отменить" скрыты с помощью needsApplyRevert.
В следующем примере показано, как использовать extraDataType для чтения или сохранения настроек, не являющихся частью сериализации ScriptedImporter, в пользовательском редакторе AssetImporterEditor.
using System;
using System.IO;
using UnityEditor;
using UnityEditor.AssetImporters;
using UnityEngine;
using Object = UnityEngine.Object;
[CustomEditor(typeof(BooleanImporter))]
[CanEditMultipleObjects]
public class BooleanImporterEditor : ScriptedImporterEditor
{
// Property to show in the custom OnInspectorGUI.
SerializedProperty m_BooleanProperty;
// override extraDataType to return the type that will be used in the Editor.
protected override Type extraDataType => typeof(BooleanClass);
// override InitializeExtraDataInstance to set up the data.
protected override void InitializeExtraDataInstance(Object extraTarget, int targetIndex)
{
var boolean = (BooleanClass)extraTarget;
// Read the boolean value from the text file and fill the extraTarget object with the data.
string fileContent = File.ReadAllText(((AssetImporter)targets[targetIndex]).assetPath);
if (!bool.TryParse(fileContent, out boolean.boolean))
{
boolean.boolean = false;
}
}
protected override void Apply()
{
base.Apply();
// After the Importer is applied, rewrite the file with the custom value.
for (int i = 0; i < targets.Length; i++)
{
string path = ((AssetImporter)targets[i]).assetPath;
File.WriteAllText(path, ((BooleanClass)extraDataTargets[i]).boolean.ToString());
}
}
public override void OnEnable()
{
base.OnEnable();
// In OnEnable, retrieve the importerUserSerializedObject property and store it.
m_BooleanProperty = extraDataSerializedObject.FindProperty("boolean");
}
public override void OnInspectorGUI()
{
// Note: you don't need to call serializedObject.Update or serializedObject.ApplyModifiedProperties
// because you are not changing the target (serializedObject) itself.
// Update the importerUserSerializedObject in case it has been changed outside the Inspector.
extraDataSerializedObject.Update();
// Draw the boolean property.
EditorGUILayout.PropertyField(m_BooleanProperty);
// Apply the changes so Undo/Redo is working.
extraDataSerializedObject.ApplyModifiedProperties();
// Call ApplyRevertGUI to show Apply and Revert buttons.
ApplyRevertGUI();
}
}
public class BooleanClass : ScriptableObject
{
public bool boolean;
}
[ScriptedImporter(0, ".boolean")]
public class BooleanImporter : ScriptedImporter
{
public override void OnImportAsset(AssetImportContext ctx)
{
string fileContent = File.ReadAllText(ctx.assetPath);
var booleanObj = ObjectFactory.CreateInstance();
if (!bool.TryParse(fileContent, out booleanObj.boolean))
{
booleanObj.boolean = false;
}
ctx.AddObjectToAsset("main", booleanObj);
ctx.SetMainObject(booleanObj);
Debug.Log("Imported Boolean value: " + booleanObj.boolean);
}
}
Вы также можете использовать настройки ScriptedImporter и дополнительные данные в том же редакторе AssetImporterEditor:
using UnityEditor;
using UnityEditor.AssetImporters;
[CustomEditor(typeof(SomeScriptedImporter))]
[CanEditMultipleObjects]
public class SomeImporterEditor : ScriptedImporterEditor
{
// ...
public override void OnInspectorGUI()
{
serializedObject.Update();
extraDataSerializedObject.Update();
// Use propertyDrawers and custom GUI for any property from both serializedObject and extraDataSerializedObject.
extraDataSerializedObject.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
ApplyRevertGUI();
}
}
[ScriptedImporter(0, ".someFile")]
public class SomeScriptedImporter : ScriptedImporter
{
public override void OnImportAsset(AssetImportContext ctx)
{
// ...
}
}
Переопределите это свойство, чтобы вернуть тип, наследуемый от ScriptableObject. Это делает AssetImporterEditor осведомленным о сериализованных данных вне импортера.
Реализация для создания собственного интерактивного пользовательского предварительного просмотра. Интерактивные пользовательские предварительные просмотры используются в области предварительного просмотра инспектора и селектора объектов.
Реализовать создание собственного пользовательского предварительного просмотра для области предварительного просмотра инспектора, заголовков основного редактора и селектора объектов.
По возвращении предыдущийредактор является редактором для targetObject или targetObjects. Функция либо возвращает значение, если редактор уже отслеживает объекты, либо уничтожает предыдущий редактор и создает новый.
Развитие и поддержание сайта требуют финансовых затрат, в первую очередь на оплату сервера и техническое обслуживание. К сожалению, собственных средств на всё это не всегда хватает, поэтому мы будем очень признательны за вашу поддержку.
Будем искренне благодарны за любое пожертвование, даже самое небольшое!
Карта Сбербанка
2202 2085 2492 4538
Номер скопирован
Карта Технобанка
4142 9830 3268 3797
Номер скопирован
Свяжитесь с администрацией, и мы подскажем, как помочь сайту.