using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Chameleon.Editor.WebAssets
{
/// Shared helpers for imported 3D models (FBX etc.).
public static class ModelImportUtil
{
///
/// Remaps every source material of an imported model to the given built materials.
/// With a single set, all slots get that material; with multiple sets, the source
/// material name is matched against the set names (substring, case-insensitive).
///
public static void RemapMaterials(string modelAssetPath, List<(string setName, Material mat)> sets)
{
if (sets == null || sets.Count == 0)
return;
var importer = AssetImporter.GetAtPath(modelAssetPath) as ModelImporter;
if (!importer)
{
Debug.LogWarning($"[PBR Import] No model importer at {modelAssetPath} — skipping material remap.");
return;
}
// Source material names = the embedded materials Unity generated on import.
var srcNames = new List();
foreach (var obj in AssetDatabase.LoadAllAssetsAtPath(modelAssetPath))
if (obj is Material m)
srcNames.Add(m.name);
if (srcNames.Count == 0)
{
Debug.LogWarning($"[PBR Import] {modelAssetPath} exposes no materials to remap.");
return;
}
foreach (var name in srcNames)
{
var target = Pick(name, sets);
if (!target)
continue;
importer.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(Material), name), target);
}
importer.SaveAndReimport();
Debug.Log($"[PBR Import] Remapped {srcNames.Count} material slot(s) on {modelAssetPath}.");
}
private static Material Pick(string srcName, List<(string setName, Material mat)> sets)
{
if (sets.Count == 1)
return sets[0].mat;
string s = srcName.ToLowerInvariant();
foreach (var (setName, mat) in sets)
if (!string.IsNullOrEmpty(setName) && s.Contains(setName.ToLowerInvariant()))
return mat;
Debug.LogWarning($"[PBR Import] Material '{srcName}' matched no texture set — using '{sets[0].setName}'.");
return sets[0].mat;
}
}
}