How to detect in code whether asset is being duplicated?

I’m trying to find a way to detect if an asset is being duplicated.

The reason why I need it is that I want to clear some serialized fields when an existing asset gets duplicated, to avoid that the duplicated asset points to the same things as the original asset. The user who duplicated it should rewire “the things” instead.

bump

bump

I looked at this a bit, but couldn’t really find anything that I’d call useful/reliable. The best I could come up with is to create an AssetPostprocessor script, which at least gives you something when an asset is duplicated. But it also gives you a bunch of noise.

public class TryFindDupes : AssetPostprocessor
{
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        Debug.Log($"OnPostprocessAllAssets. importedAssets: {importedAssets.Length}; deletedAssets: {deletedAssets.Length}; movedAssets: {movedAssets.Length}; movedFromAssetPaths: {movedFromAssetPaths.Length}");

        Action<string, string[]> action = (name, array) =>
        {
            if (array.Length > 0)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    Debug.Log($"{name}: {array[i]}");
                }
            }
        };
        action("importedAssets", importedAssets);
        action("deletedAssets", deletedAssets);
        action("movedAssets", movedAssets);
        action("movedFromAssetPaths", movedFromAssetPaths);
    }
}

If I duplicate some asset named “ABCDE.mat” with this code in my project, I get the following output:

This tells me that you’ll at least know that an asset was possibly duplicated by looking at what’s in importedAssets. However, it will also trigger on any kind of asset import, and it seems that duplicating an object reimports the original object, which is why you see it showing up here, so I don’t know how you’d even know that this was the result of asset duplication, or just any other reason an asset was imported.

Sorry for not being much help on this. It seems that Unity is just missing the wiring to inform us of duplication events, unless I just haven’t found the API for it.

1 Like

Thanks for looking into it! That was a good idea with the asset postprocessor, but as you mentioned, it seems a bit too unreliable.

That’s really odd that there seem to exist no API for that.