Search Unity

Question Saving a mesh with AssetDatabase.CreateAsset causes all Mesh Filters to lose reference

Discussion in 'Asset Database' started by Botaurus, Feb 5, 2023.

  1. Botaurus

    Botaurus

    Joined:
    Feb 20, 2013
    Posts:
    81
    Running this code twice causes all mesh filter's that referenced the file that was saved over to lose reference.
    Is there a better way of doing this so that mesh filter's dont lose their reference?
    Thank you


    upload_2023-2-5_9-35-15.png

    Code (CSharp):
    1.         [MenuItem("Create/Damage Number Mesh")]
    2.         public static void SaveMesh()
    3.         {
    4.          ...
    5.             // Create mesh
    6.             Mesh mesh = new Mesh();
    7.             ...
    8.             // Save mesh to project folder
    9.             AssetDatabase.CreateAsset(mesh, "Assets/Game/MyMesh.asset");
    10.             AssetDatabase.SaveAssets();
    11.         }
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,989
    That's expected. You are creating a new asset every time. Instead, once the mesh exists as an asset file, you would LoadAsset that mesh and modify it, then save it.
     
    Unity_Javier likes this.
  3. Botaurus

    Botaurus

    Joined:
    Feb 20, 2013
    Posts:
    81
    ah that makes sense, thank you!
     
  4. madtowngaming

    madtowngaming

    Joined:
    Oct 7, 2020
    Posts:
    2
    THIS DOES NOT WORK .. if you load the created mesh asset and make changes to it and then save it NOTHING IS SAVED .. the mesh remains empty of all data except the vertex position data ...
    The saved asset seems to always ignore any changes made to it .. WHY???
     
  5. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,989
    CODE???