Skip to content

Instantly share code, notes, and snippets.

@joshcamas
Created September 9, 2020 18:02
Show Gist options
  • Save joshcamas/54815ae14b52a482880dd12d8943e1b7 to your computer and use it in GitHub Desktop.
Save joshcamas/54815ae14b52a482880dd12d8943e1b7 to your computer and use it in GitHub Desktop.
Automatically applies preset to folders recursively
using UnityEditor;
using UnityEditor.Presets;
using System.IO;
namespace Ardenfall
{
/// <summary>
/// Post Processer that automatically finds the nearest preset
/// (first checks in self directory, then goes up the parent chain) and applies it
/// </summary>
public class AutoPresetAssetPostProcesser : AssetPostprocessor
{
void OnPreprocessAsset()
{
// Make sure we are applying presets the first time an asset is imported.
if (assetImporter.importSettingsMissing)
{
// Get the current imported asset folder.
var path = Path.GetDirectoryName(assetPath);
while (!string.IsNullOrEmpty(path))
{
// Find all Preset assets in this folder.
var presetGuids = AssetDatabase.FindAssets("t:Preset", new[] { path });
foreach (var presetGuid in presetGuids)
{
// Make sure we are not testing Presets in a subfolder.
string presetPath = AssetDatabase.GUIDToAssetPath(presetGuid);
if (Path.GetDirectoryName(presetPath) == path)
{
// Load the Preset and try to apply it to the importer.
var preset = AssetDatabase.LoadAssetAtPath<Preset>(presetPath);
if (preset.ApplyTo(assetImporter))
return;
}
}
// Try again in the parent folder.
path = Path.GetDirectoryName(path);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment