Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

AssetDatabase.CopyAsset changes GUID of target

Discussion in 'Asset Database' started by StephenCox, Jul 12, 2018.

  1. StephenCox

    StephenCox

    Joined:
    Oct 26, 2016
    Posts:
    3
    We have a script that calls AssetDatabase.CopyAsset to overwrite an existing asset but when this happens Unity assigns a new GUID to the target asset breaking any references to the target asset in Unity.

    Is there a reason the CopyAsset function modifies the target asset's GUID? It was my understanding that this was an extremely bad thing to do in Unity and I'm a little surprised that Unity itself is doing it.
     
    unity_SBt0djhrxNe9mA likes this.
  2. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,438
    It handles it as a new asset and every asset must have an unique identifier, thus it created a new guid. If you want to replace the content of an existing asset, use EditorUtility.CopySerialized instead.
    https://docs.unity3d.com/ScriptReference/EditorUtility.CopySerialized.html
     
  3. StephenCox

    StephenCox

    Joined:
    Oct 26, 2016
    Posts:
    3
    My question is why does it handle it as a new asset? It's an existing asset with its own GUID that simply gets discarded and replaced, breaking all references in Unity.
     
  4. unity_SBt0djhrxNe9mA

    unity_SBt0djhrxNe9mA

    Joined:
    Feb 28, 2021
    Posts:
    3
    For me simple file copying worked as expected (at least I am not aware of some destructive side-effects):
    Code (CSharp):
    1.  
    2. private static bool CopySceneAsset(string path, string newPath)
    3. {
    4.     var fullPath = Path.Combine(Application.dataPath, "..", path);
    5.     if (!File.Exists(fullPath))
    6.     {
    7.         Debug.LogError(path + ": file not found.");
    8.         return false;
    9.     }
    10.    
    11.     var fullNewPath = Path.Combine(Application.dataPath, "..", newPath);
    12.     if (File.Exists(fullNewPath))
    13.     {
    14.         File.Copy(fullPath, fullNewPath, true);
    15.         return true;
    16.     }
    17.     else
    18.     {
    19.         return AssetDatabase.CopyAsset(path, newPath);
    20.     }
    21. }
    22.  
     
    amjaliks and singoonx like this.
  5. wqaetly

    wqaetly

    Joined:
    Oct 25, 2018
    Posts:
    6
    EditorUtility.CopySerialized is not a useful API,Because when your original asset changed and execute EditorUtility.CopySerialized, the target asset is not update
     
  6. tutorial4unity

    tutorial4unity

    Joined:
    Apr 14, 2019
    Posts:
    14
    Hi, so just a couple more lines will work for you but are you still looking? Weird such an old post is showing up top.