Could not load copied asset via AssetDatabase.LoadAssetAtPath

I am using AssetDatabase.CopyAsset method to create a copy of a prefab as part of an AssetPostProcessor implementation:

AssetDatabase.CopyAsset(sourcePrefabLocation, targetPrefabLocation);
AssetDatabase.ImportAsset(
    targetPrefabLocation, 
    ImportAssetOptions.DontDownloadFromCacheServer|ImportAssetOptions.ForceUpdate);
AssetDatabase.SaveAssets();

This works fine, the asset is copied. However, later in the same post-processor, I want to load the copied asset, so I am using:

GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(targetPrefabLocation);

Unfortunately, the prefab variable is always null. I used the following code to list all prefab assets, just to find out that the copied prefab is not enlisted. That would actually explain why the LoadAssetAtPath fails to load the asset.

AssetDatabase.GetAllAssetPaths().Where(x => x.Contains(".prefab")).Aggregate(new StringBuilder().AppendLine(), (sb, s) => sb.AppendLine(s))

So, what should I do to make the AssetDatabase include the copied asset?

@ivaylo5ev

I found a solution to this problem:
`
string oldpath = {XXXX};

string newpath = {XXX};

AssetDatabase.CopyAsset(oldpath, newpath);

AssetDatabase.SaveAssets();

AssetDatabase.Refresh();

AssetDatabase.ImportAsset(newpath);

AssetDatabase.LoadXXX // It can get the right asset now
`

@ivaylo5ev Hello there, probably you need to “Refresh” the project so the new asset shows up, there is a method to do that, cheers.

Had the same problem once.
Then I changed to used GameObject prefab = AssetDatabase.LoadAssetAtPath(targetPrefabLocation,typeof(GameObject)) as GameObject; and it works for me.

Did you find a solution for this, I have the same problem, I copy texture files into the project but it seems Unity waits till after the OnPostProcessAllAssets completes before it actually does import the textures into the asset database. Even using Refresh etc. makes no difference, I can’t see a way to force Unity to import the textures now and update the database so I can make changes to them.