Skip to content

Instantly share code, notes, and snippets.

@edwardrowe
Last active December 2, 2019 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardrowe/51fab9f899339b9da3339d4cc599b07f to your computer and use it in GitHub Desktop.
Save edwardrowe/51fab9f899339b9da3339d4cc599b07f to your computer and use it in GitHub Desktop.
Unity AssetPostProcessor to Identify Duplicate Assets of a Type
using System.Collections.Generic;
using RedBlueGames.Tools.SaveGame;
using UnityEngine;
using UnityEditor;
/// <summary>
/// Assign new SavableGUIDs when they are imported
/// </summary>
public class SaveableGUIDImporter : AssetPostprocessor
{
private static List<string> preProcessedAssets;
private static List<string> PreProcessedAssets
{
get
{
if (preProcessedAssets == null)
{
preProcessedAssets = new List<string>();
}
return preProcessedAssets;
}
}
void OnPreprocessAsset()
{
var asset = AssetDatabase.LoadAssetAtPath(assetImporter.assetPath, typeof(SaveableScriptableObject));
if (asset == null)
{
PreProcessedAssets.Add(assetImporter.assetPath);
}
}
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (string str in importedAssets)
{
if (PreProcessedAssets.Contains(str))
{
var asset = AssetDatabase.LoadAssetAtPath(str, typeof(SaveableScriptableObject));
if (asset is SaveableScriptableObject)
{
var assetAsSSO = (SaveableScriptableObject)asset;
var allSaveableSOs = LoadAllSaveableScriptableObjects();
foreach (var existingScriptableObject in allSaveableSOs)
{
if (existingScriptableObject.SaveableGUID == assetAsSSO.SaveableGUID &&
existingScriptableObject.name != asset.name)
{
assetAsSSO.EditorOnly_ResetGUID();
EditorUtility.SetDirty(asset);
Debug.Log($"Reset GUID on asset: {str} because it matched existing asset: {existingScriptableObject.name}");
}
}
}
PreProcessedAssets.Remove(str);
}
}
PreProcessedAssets.Clear();
}
private static List<SaveableScriptableObject> LoadAllSaveableScriptableObjects()
{
var allSaveableSOs = new List<SaveableScriptableObject>();
{
var allSaveableSOGUIDs = UnityEditor.AssetDatabase.FindAssets("t: SaveableScriptableObject");
foreach (var guid in allSaveableSOGUIDs)
{
var soPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
var so = (SaveableScriptableObject)UnityEditor.AssetDatabase.LoadAssetAtPath(soPath, typeof(SaveableScriptableObject));
allSaveableSOs.Add(so);
}
}
return allSaveableSOs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment