Search Unity

loading a Mesh from a .asset file?

Discussion in 'Scripting' started by verheijden, Oct 18, 2016.

  1. verheijden

    verheijden

    Joined:
    Mar 12, 2016
    Posts:
    6
    So I'm saving a 3d Mesh in to a . asset file (obj_test.asset) using this code:

    Code (CSharp):
    1. string meshPath = AssetDatabase.GenerateUniqueAssetPath("Assets/downloads/obj_"+fileName+".asset");
    2. Mesh myMesh = tempObj.GetComponent<MeshFilter>().sharedMesh;
    3. AssetDatabase.CreateAsset(myMesh, meshPath);
    4. AssetDatabase.SaveAssets();
    and that works great... but the only problem is i cant seem to load the mash back in to unity at runtime, how do i convert a .asset file to a useable game object?
     
  2. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    633
    Hi there, you need to either keep a reference to it, for example you can create a ReferenceHolder component using the singleton pattern and with a public Mesh yourMesh: field, add it to a gameobject your turn into a prefab which you add to your scenes.

    Alternatively you can put it in a "resources" folder to use the "Resources.Load" API but that means you have to manage the lifetime of the asset, not an issue on smaller projects but bigger projects that want to run on x86 have to think it through.
     
  3. verheijden

    verheijden

    Joined:
    Mar 12, 2016
    Posts:
    6
    hi met i'm trying the prefab way:

    Code (CSharp):
    1. AssetDatabase.CreateAsset(myMesh, meshPath);
    2. AssetDatabase.SaveAssets();
    3. AssetDatabase.Refresh();
    4.  
    5. object prefab = EditorUtility.CreateEmptyPrefab("Assets/downloads/" + fileName + ".prefab");
    6. UnityEditor.PrefabUtility.ReplacePrefab(myMesh, prefab, ReplacePrefabOptions.ConnectToPrefab);
    but its throwing this error:
     
  4. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    633
    Let me rephrase it, wasn't trying to imply you should procedurally create a prefab out of a mesh. Prefabs are an asset version of a GameObject hierarchy.

    In what I describe, going through a prefab isn't even mandatory, just felt right since it may then be used accross several scenes if that's of any use to your project.

    The key part was the reference holder component, which can be a very simple script with only a public mesh blabla; or public list<mesh> blabla: field based on your needs.

    The gameobject with the reference holder component you make once and manually in unity. Up to you to choose if you wish to store it as a prefab or an object of your scene.

    What you can script is wiring the mesh with the field in the component.