Rule-driven Unity 6 Editor pipeline and UI Toolkit compliance workbench for Sprites, UI textures, general textures, 3D Models, and Audio clips. It enforces team-configured AssetImportPolicyAsset rules automatically via AssetPostprocessor, audits existing project assets with non-destructive Current -> Expected property diffs, and supports custom IAssetImportRule extensions discovered via TypeCache.
- Non-destructive property overrides (
RuleOverride<T>): Every importer field in a rule carries an explicitenabledflag (RuleOverride<T>.On(...)/RuleOverride<T>.Off(...)) so rules modify only opted-in settings and preserve artist choices on everything else. - Built-in rules for Textures/Sprites/UI, 3D Models, and Audio:
- Textures, Sprites, and UI (
TextureImportRuleConfig/TextureRuleProcessor):textureType,spriteImportMode,spritePixelsPerUnit,mipmapEnabled,isReadable,filterMode,wrapMode,alphaIsTransparency,maxTextureSize,textureCompression,crunchedCompression,npotScale, and optional per-platform overrides (PlatformTextureOverrideConfigfor targets such asAndroid,iPhone, orStandalone). - 3D Models (
ModelImportRuleConfig/ModelRuleProcessor):globalScale,useFileScale,meshCompression,isReadable,optimizeMeshPolygons,optimizeMeshVertices,importCameras,importLights,importVisibility,importBlendShapes,animationType,importAnimation,materialImportMode, andgenerateSecondaryUV. - Audio Clips (
AudioImportRuleConfig/AudioRuleProcessor):forceToMono,loadInBackground,ambisonic, and default sample settings (loadType,compressionFormat,quality,sampleRateSetting, andsampleRateOverride).
- Textures, Sprites, and UI (
- Folder prefix and glob path matching (
AssetPathMatcher): Target assets by plain folder prefixes, glob patterns (*,**,?), case-insensitive file extension lists, per-ruleexcludePatterns, global ignore patterns (**/Editor/**,**/Gizmos/**,**/*_raw.*by default), and Unity Asset Labels (ImportRulesIgnoreby default). - Starter policy presets (
AssetImportPolicyAsset): One-click generators forMobile 2D/UI/Audio,PC 3D URP, andPixel Artproject defaults. - UI Toolkit workbench (
AssetImportRulesWindow): Dockable window (Tools > HaruChanZ64 > Assets > AssetImportRules > Import Policy Workbench) with three tabs: Policy & Presets, Compliance Audit (dry-run scan, category filtering, per-asset Ping/Fix, batch Apply & Reimport All, Markdown clipboard copy, JSON export), and Path Rule Tester. - Extensible rule engine (
IAssetImportRule): ImplementIAssetImportRulein any Editor assembly to add studio-specific naming checks or custom importer logic;UnityEditor.TypeCachediscovers concrete types automatically. - Optional pre-build compliance guard (
ImportAuditBuildGuard): ImplementsIPreprocessBuildWithReport(callbackOrder = 15, disabled by default inEditorPrefs) to warn or fail player builds (BuildFailedException) when non-compliant assets exist.
- Unity
6000.0or newer - Editor-only package (
AssetImportRules.Editorcompiles only for theEditorplatform; zero runtime footprint) - Zero required external dependencies
- Open Window > Package Manager in Unity 6 (
6000.0+). - Click + (top-left) and choose Install package from git URL....
- Enter:
https://github.com/haruchanz64/AssetImportRules.git
Add the package path to Packages/manifest.json:
{
"dependencies": {
"com.haruchanz64.asset-import-rules": "file:../Plugins/AssetImportRules"
}
}- Open Tools > HaruChanZ64 > Assets > AssetImportRules > Import Policy Workbench.
- In the Policy & Presets tab, click Create Mobile 2D/UI/Audio Policy, Create PC 3D URP Policy, or Create Pixel Art Policy (or create a blank policy via Assets > Create > AssetImportRules > Import Policy and assign it to Policy Asset).
- Review or edit rules directly in the embedded Inspector, and set
Enforcement Mode(AutoApplyOnImport,AuditOnly, orDisabled). - Switch to Compliance Audit and click Scan Project (Dry Run) to view the compliance score and exact
Current -> Expecteddiffs without modifying any assets. - Click Fix on individual rows or Apply & Reimport All to enforce matching rules in a single
AssetDatabase.StartAssetEditing()batch. - Use the Path Rule Tester tab to test sample asset paths against global ignore patterns and built-in rule priorities before rolling out changes.
- Add the
ImportRulesIgnoreUnity Asset Label (or match aglobalIgnorePatternsentry such as**/*_raw.*) on any hero asset that should be exempt from automatic overrides.
- Active policy resolution (
AssetComplianceAuditor.GetActivePolicy): Reads the selected policy GUID fromEditorPrefs(AssetImportRules.ActivePolicyGuid). If unset or missing, it falls back to the firstAssetImportPolicyAssetfound viaAssetDatabase.FindAssets("t:AssetImportPolicyAsset"). - Automatic import hook (
AssetImportRulesPostprocessor): HooksOnPreprocessTexture,OnPreprocessModel, andOnPreprocessAudio. When the active policy usesImportEnforcementMode.AutoApplyOnImportand the asset is not exempt, all matching built-in rules run in ascendingpriorityorder, followed by discoveredIAssetImportRuleextensions in ascendingPriorityorder. Because rules run in ascending order, higher priority values apply later and win on overlapping properties. - Dry-run audit vs. batch apply:
AssetComplianceAuditor.RunDryRunAudit(policy, rootFolder)inspectst:Texture t:Model t:AudioClipassets without modifying any importer and computescomplianceScore = round(compliantAssets / matchedAssets * 100)(or100when zero assets match).AssetComplianceAuditor.ApplyPolicyToAssetPaths(policy, paths)wraps updates inAssetDatabase.StartAssetEditing()/StopAssetEditing()and callsSaveAndReimport()only on importers that actually changed.
AssetPathMatcher.Matches normalizes backslashes to forward slashes and evaluates rules in three stages:
- Exemptions and exclusions:
AssetComplianceAuditor.IsAssetExemptfirst checkspolicy.globalIgnorePatternsandpolicy.exemptAssetLabel. Each rule then evaluates its ownexcludePatterns. - Extensions: If
extensionsis non-empty, the asset extension must match one entry (case-insensitive, with or without leading.). - Path pattern: Plain folder prefixes (no
*or?) match the folder and its descendants; glob patterns translate**/(zero or more directories),**(any characters),*(single segment), and?(single non-slash character) into an anchored case-insensitive regex.
Place a concrete class implementing IAssetImportRule with a public parameterless constructor inside any Editor assembly. AssetComplianceAuditor.DiscoverCustomRules() discovers it automatically through TypeCache:
using System.Collections.Generic;
using AssetImportRules.Editor.Core;
using UnityEditor;
public sealed class MaxLightmappedModelScaleRule : IAssetImportRule
{
public string RuleId => "STUDIO_MODEL_UV2";
public string DisplayName => "Environment Models Generate Lightmap UVs";
public int Priority => 40;
public bool Matches(string assetPath, AssetImporter importer)
{
return importer is ModelImporter &&
AssetPathMatcher.Matches(assetPath, "Assets/Environment/**", new[] { ".fbx" });
}
public void Audit(string assetPath, AssetImporter importer, List<ImportDiffEntry> diffs)
{
var model = (ModelImporter)importer;
if (!model.generateSecondaryUV)
{
diffs.Add(new ImportDiffEntry
{
ruleName = DisplayName,
propertyName = "generateSecondaryUV",
currentValue = "False",
expectedValue = "True"
});
}
}
public bool Apply(string assetPath, AssetImporter importer)
{
var model = (ModelImporter)importer;
if (model.generateSecondaryUV) return false;
model.generateSecondaryUV = true;
return true;
}
}Call AssetComplianceAuditor and ImportAuditExporter from an Editor script or Unity -executeMethod CI entrypoint:
using System.IO;
using AssetImportRules.Editor.Core;
using AssetImportRules.Editor.Pipeline;
using UnityEditor;
using UnityEngine;
public static class ImportComplianceCi
{
public static void RunAuditAndExport()
{
AssetImportPolicyAsset policy = AssetComplianceAuditor.GetActivePolicy();
if (policy == null)
{
Debug.LogError("No AssetImportPolicyAsset found in project.");
return;
}
ImportComplianceReport report = AssetComplianceAuditor.RunDryRunAudit(policy, "Assets");
File.WriteAllText("import_compliance.md", ImportAuditExporter.ToMarkdown(report));
File.WriteAllText("import_compliance.json", ImportAuditExporter.ToJson(report, prettyPrint: true));
Debug.Log($"Import compliance: {report.complianceScore}/100 ({report.nonCompliantAssets} non-compliant).");
}
}using AssetImportRules.Editor.Core;
using AssetImportRules.Editor.Pipeline;
using UnityEditor;
using UnityEngine;
public static class PolicyBootstrap
{
public static void CreateAndActivatePolicy()
{
var policy = ScriptableObject.CreateInstance<AssetImportPolicyAsset>();
policy.enforcementMode = ImportEnforcementMode.AutoApplyOnImport;
policy.ApplyPc3DUrpPreset();
AssetDatabase.CreateAsset(policy, "Assets/Settings/AssetImportPolicy_PC.asset");
AssetDatabase.SaveAssets();
AssetComplianceAuditor.SetActivePolicy(policy);
ImportAuditBuildGuard.Enabled = true;
ImportAuditBuildGuard.FailOnNonCompliant = true;
}
}| Type | Namespace | Purpose | Built-in implementation |
|---|---|---|---|
IAssetImportRule |
AssetImportRules.Editor.Core |
Extension contract (Matches, Audit, Apply) auto-discovered via TypeCache |
SampleNoSpacesInAssetNameRule (in sample) |
AssetImportPolicyAsset |
AssetImportRules.Editor.Core |
ScriptableObject storing enforcement mode, exemptions, rule lists, and starter presets | ApplyMobile2DAndUiPreset, ApplyPc3DUrpPreset, ApplyPixelArtPreset |
RuleOverride<T> |
AssetImportRules.Editor.Core |
Opt-in value wrapper (enabled + value) for non-destructive importer overrides |
RuleOverride<T>.On(...), RuleOverride<T>.Off(...) |
AssetPathMatcher |
AssetImportRules.Editor.Core |
Pure C# normalizer and folder-prefix/glob/extension/exclusion matcher | NormalizePath, Matches, MatchesSinglePattern |
ImportComplianceReport |
AssetImportRules.Editor.Core |
Serializable audit result containing counts, complianceScore, and AssetAuditItem diffs |
ComputeScore |
AssetComplianceAuditor |
AssetImportRules.Editor.Pipeline |
Active policy lookup, custom rule discovery, exemption checks, dry-run audits, and batch apply | GetActivePolicy, RunDryRunAudit, ApplyPolicyToAssetPaths |
TextureRuleProcessor / ModelRuleProcessor / AudioRuleProcessor |
AssetImportRules.Editor.Pipeline |
Type-specific importer audit and apply processors | Audit, Apply |
AssetImportRulesPostprocessor |
AssetImportRules.Editor.Pipeline |
AssetPostprocessor applying active policy on Texture, Model, and Audio import |
OnPreprocessTexture, OnPreprocessModel, OnPreprocessAudio |
ImportAuditExporter |
AssetImportRules.Editor.Pipeline |
Serializes ImportComplianceReport to Markdown or JSON |
ToMarkdown, ToJson |
ImportAuditBuildGuard |
AssetImportRules.Editor.Pipeline |
Optional IPreprocessBuildWithReport hook to warn or fail builds on violations |
Enabled, FailOnNonCompliant, OnPreprocessBuild |
AssetImportRulesWindow |
AssetImportRules.Editor.UI |
UI Toolkit workbench for policy authoring, auditing, and path testing | ShowWindow |
Import Custom Import Rule Sample (Samples~/CustomRule) from the Package Manager Samples tab:
SampleNoSpacesInAssetNameRule: audit-onlyIAssetImportRule(RuleId = "TEAM_NAME_01",Priority = 50) checking that assets underAssets/Art/**do not contain spaces in their filenames and suggesting underscore-separated replacements in audit diffs.
The package includes EditMode NUnit tests under Tests/Editor/ runnable from Window > General > Test Runner (EditMode tab):
Tests/Editor/AssetPathMatcherTests.cs: verifies folder prefix matching, glob wildcards (**,*), case-insensitive extension filtering, exclusion patterns, and starter rule generation inApplyMobile2DAndUiPreset().Tests/Editor/ImportRuleAuditTests.cs: creates a temporary misconfigured PNG texture under a temporaryAssets/folder, verifies dry-run non-compliance detection and Markdown/JSON report export, runsApplyPolicyToAssetPaths, and confirms the post-fix audit reaches a100compliance score.
- Active policy selection and pre-build guard toggles are stored in
EditorPrefs:AssetComplianceAuditor.SetActivePolicy,ImportAuditBuildGuard.Enabled, andImportAuditBuildGuard.FailOnNonCompliantare per-machine Editor preferences rather than fields onAssetImportPolicyAsset. On CI runners or fresh checkouts,GetActivePolicy()falls back to the firstAssetImportPolicyAssetfound in the project, andImportAuditBuildGuard.Enableddefaults tofalseunless set by your build script. - Custom
IAssetImportRuleclasses are not showing up: Ensure the class is in an Editor assembly, is concrete (notabstractor an interface), and has a public parameterless constructor. Instantiation exceptions are logged as warnings with the[AssetImportRules]prefix. - Dry-run audit scope is limited to Textures, Models, and AudioClips:
RunDryRunAuditqueriesAssetDatabase.FindAssets("t:Texture t:Model t:AudioClip", ...), andAssetImportRulesPostprocessorhooksOnPreprocessTexture,OnPreprocessModel, andOnPreprocessAudio. CustomIAssetImportRuleimplementations targeting other asset types will not be visited by the built-in scanner or postprocessor. - Overlapping rules with conflicting values keep reporting diffs:
ApplyRulesToImporterruns matching rules in ascending priority order (higher priority overwrites lower priority), whileRunDryRunAuditchecks every matching rule independently. If two overlapping rules enable the same property with different target values, add anexcludePatternsentry to the lower-priority rule or disable the conflicting override. - Exempting newly imported assets on first import:
AssetImportRulesPostprocessorchecksexemptAssetLabelviaAssetDatabase.LoadMainAssetAtPathandAssetDatabase.GetLabels. Brand-new files do not carry Unity Asset Labels until after their initial import; useglobalIgnorePatterns(such as**/*_raw.*) to exempt assets before first import. - Platform texture
compressionQualityvs. dry-run diffs:TextureRuleProcessor.ApplyupdatescompressionQualitywhen it differs, whereasTextureRuleProcessor.Auditchecksoverridden,maxTextureSize, andformatfor platform overrides. ApplyPixelArtPreset()only replacestextureRules: UnlikeApplyMobile2DAndUiPreset()andApplyPc3DUrpPreset(), callingApplyPixelArtPreset()leaves existingmodelRulesandaudioRulesunchanged.- Audio
qualityrange andsampleRateOverridefloor:AudioRuleProcessor.Applyclampsqualityto[0, 1]andsampleRateOverrideto a minimum of8000Hz. Keep configuredqualityvalues within[0, 1]so dry-run audits match applied values.