Skip to content

Instantly share code, notes, and snippets.

@probablyspoonie
Created June 27, 2020 15:45
Show Gist options
  • Select an option

  • Save probablyspoonie/ff514a10405f60521e7ae0c2215fa939 to your computer and use it in GitHub Desktop.

Select an option

Save probablyspoonie/ff514a10405f60521e7ae0c2215fa939 to your computer and use it in GitHub Desktop.
using System;
using UnityEditor;
//NOTE: Must be placed under a folder named "Editor" as it is a Unity editor script
public class ModelPostProcessor : AssetPostprocessor
{
static readonly string[] supportedFileExtensions = new string[] { ".fbx", ".blend" };
//-------------------------------------------------------------------------------------- EASIEST WAY
public void OnPreprocessModel()
{
ModelImporter importer = assetImporter as ModelImporter;
String name = importer.assetPath.ToLower();
if (IsSupportedExtension(assetPath))
{
//Standard unity way
importer.materialImportMode = ModelImporterMaterialImportMode.ImportStandard;
importer.materialLocation = ModelImporterMaterialLocation.External;
importer.materialName = ModelImporterMaterialName.BasedOnMaterialName;
importer.materialSearch = ModelImporterMaterialSearch.Everywhere;
//Alternate way
//importer.materialImportMode = ModelImporterMaterialImportMode.None;
}
}
private bool IsSupportedExtension(string assetPath)
{
for (int i = 0; i < supportedFileExtensions.Length; i++)
{
if (assetPath.EndsWith(supportedFileExtensions[i]))
{
return true;
}
}
return false;
}
//-------------------------------------------------------------------------------------- ALTERNATE WAY
/*
static readonly string[] materialLocations = new string[] { "Assets/Project/Materials/" };
// Alternative way of looking at specific folders
public Material OnAssignMaterialModel(Material material, Renderer renderer)
{
for (int i = 0; i < materialLocations.Length; i++)
{
//Local path (For AssetDatabase use)
string matPath = Path.Combine(materialLocations[i], material.name + ".mat");
//Disk path (for System.IO use)
string drivePath = matPath.Remove(matPath.IndexOf("Assets/"), "Assets/".Length);
drivePath = Path.Combine(Application.dataPath, drivePath);
Log("Trying to find " + material.name + " at " + drivePath);
bool assetExists = File.Exists(drivePath);
if (assetExists)
{
if (AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)))
return AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
}
}
Log("Could not find material!!!", "red");
return AssetDatabase.LoadAssetAtPath("Assets/Project/Materials/Default.mat", typeof(Material)) as Material;
}
void Log(string text, string color = "grey")
{
Debug.Log(string.Format("<color={1}>[Material Processing] {0}</color>", text, color));
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment