Search Unity

[FREE] Runtime OBJ Loader

Discussion in 'Assets and Asset Store' started by aaro4130, Nov 4, 2015.

  1. DeusMarcus

    DeusMarcus

    Joined:
    Apr 6, 2017
    Posts:
    1
    Hi,
    Thanks for this asset.

    I have the same problem.

    I have to load model which has more than 64k vertices and I can't change that...

    Could you tell me how can I break the single mesh
    into sub meshes at runtime ? Thanks for the reply.
     
  2. dannox

    dannox

    Joined:
    Oct 20, 2010
    Posts:
    12
    Hi,
    I use that filter for loading obj (in particular a chair) but I see that texture mapping or normals, are wrong.
    In attach the correct image and the wrong one.
     

    Attached Files:

  3. saadjumani

    saadjumani

    Joined:
    Apr 12, 2016
    Posts:
    10
    Can you make a simple tutorial on how to use that in-game? cuz I seem to be having difficulty figuring it out
     
  4. resindraburiza

    resindraburiza

    Joined:
    Jul 7, 2017
    Posts:
    2
    @saadjumani , can you finally figure it out how to use this importer? I'm also having difficulty using this importer. Or is there anyone can give me hint to use this importer?
     
  5. resindraburiza

    resindraburiza

    Joined:
    Jul 7, 2017
    Posts:
    2
    Dear @aaro4130 , I can't import my obj files. I look to your code and it seems that if my obj file does not have 'usemtl' it will fail to import. Is it correct? Because if the obj file does not have 'usemtl' line, the foreach "foreach (string mn in materialNames)" will not executed because matrialNames is empty. Can you suggest any fix? Thank you.
     
  6. CHANCENAAA

    CHANCENAAA

    Joined:
    Jan 27, 2017
    Posts:
    2
    Hi @aaro4130 would u be able to provide us more detailed information about separating meshes in runtime? I tried to write my own script but it was tossing out the invalid index. Would you be able to give me some detailed explanation on how to seperate meshes runtime
     
  7. mezzostatic

    mezzostatic

    Joined:
    Aug 18, 2016
    Posts:
    13
    BUG REPORT!!!!

    Hey everyone, just to let others know what bugs they may find in the current version... it doesnt give error messages when it not can import a mesh, so i coudlnt load the first 4 object files.

    It needs MTL next to the object or it fails, objects with partial MTL will cause stuff to be loaded incomplketely.

    Also it not successful to show all the OBJ for other random reasons i didn't understand yet.

    It should be easy and trivial to code around that, so that MTL files get ignored if you dont need them.. but I didnt figure it out.
     
    Last edited: Jul 25, 2017
  8. mezzostatic

    mezzostatic

    Joined:
    Aug 18, 2016
    Posts:
    13
    this failed to work for 5/5 obj tests, i loads half files or fails where ther eisnt a mtl.


    used the ObjLoaderObjLoaderObjLoaderObjLoaderObjLoader wiki script in the end, the fast one didnt work, the slow one i used with this ok :

    using UnityEngine;
    using System.Collections;

    public class NewBehaviourScript : MonoBehaviour {
    public Mesh myMesh;
    // Use this for initialization
    void Start () {
    MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
    ObjLoader rew= new ObjLoader();
    meshFilter.mesh = rew.ImportFile("E:/OLD DESKTOP/morphgen/Assets/morphgen/DONE/1280ball.obj");
    }

    // Update is called once per frame
    void Update () {

    }
    }
     
  9. vuluongthanh

    vuluongthanh

    Joined:
    Nov 23, 2013
    Posts:
    16
    Code (CSharp):
    1. Dictionary<string, int> faceCountDict = new Dictionary<string, int> ();//for counting how many OBJFace added relate to meshname
    2. const int MAX_VERTICLES_PER_MESH = 64990 * 3;
    3. // some parse code.
    4. // Go to this line and change it: if (indexes.Length < 5 && indexes.Length >= 3)
    5. //==================================
    6. if (indexes.Length < 5 && indexes.Length >= 3) {
    7.                         OBJFace f1 = new OBJFace ();
    8.                         f1.materialName = cmaterial;
    9.                         f1.indexes = new int[] { indexes [0], indexes [1], indexes [2] };
    10.                         f1.meshName = (splitByMaterial) ? cmaterial : cmesh;
    11.                         f1.meshName = GenOverMaxVerticesMeshName (f1.meshName, faceList);
    12.  
    13.                         if (!objectNames.Contains (f1.meshName)) {
    14.                             objectNames.Add (f1.meshName);
    15.                         }
    16.  
    17.                         if(!faceCountDict.ContainsKey(f1.meshName)){
    18.                             faceCountDict.Add (f1.meshName, 0);  
    19.                         }
    20.                         faceCountDict [f1.meshName] = faceCountDict [f1.meshName] + 1;
    21.                         faceList.Add (f1);
    22.  
    23.                      
    24.                         if (indexes.Length > 3) {
    25.                             OBJFace f2 = new OBJFace ();
    26.                             f2.materialName = cmaterial;
    27.                             f2.meshName = (splitByMaterial) ? cmaterial : cmesh;
    28.                             f2.indexes = new int[] { indexes [2], indexes [3], indexes [0] };
    29.                             f2.meshName = GenOverMaxVerticesMeshName (f2.meshName, faceList);
    30.  
    31.                             if (!objectNames.Contains (f2.meshName)) {
    32.                                 objectNames.Add (f2.meshName);
    33.                             }
    34.  
    35.                             if(!faceCountDict.ContainsKey(f2.meshName)){
    36.                                 faceCountDict.Add (f2.meshName, 0);  
    37.                             }
    38.                             faceCountDict [f2.meshName] = faceCountDict [f2.meshName] + 1;
    39.                             faceList.Add (f2);
    40.                         }
    41.                     }
    42.  
    43. //============================
    44. string GenOverMaxVerticesMeshName (string meshName, List<OBJFace> faceList)
    45.     {
    46.         string newName = "";
    47.         if (!faceCountDict.ContainsKey (meshName) || faceCountDict [meshName] < (MAX_VERTICLES_PER_MESH / 3)) {
    48. //            Debug.LogWarning (meshName + " -- " + (faceCountDict.ContainsKey (meshName) ? faceCountDict [meshName] : 0));
    49.             return meshName;
    50.         }
    51.         else {
    52.             int count = 1;  
    53.             newName = meshName + "##" + count;
    54.             if (!faceCountDict.ContainsKey (newName))
    55.                 faceCountDict.Add (newName, 0);
    56.             while (faceCountDict[newName] > (MAX_VERTICLES_PER_MESH / 3)) {
    57. //                Debug.LogWarning ("Gen next: " + newName + " -- " + faceCountDict [newName]);
    58.                 count += 1;
    59.                 newName = meshName + "##" + count;
    60.                 if (!faceCountDict.ContainsKey (newName))
    61.                     faceCountDict.Add (newName, 0);
    62.             }
    63.         }
    64. //        Debug.LogWarning (newName + " -- " + faceCountDict [newName]);
    65.         return newName;
    66.     }
    Hope this help.
    I solved this problem by add new OBJFace with new mesh name. And then do some change in build mesh. Here's my code:
     
    Rajawat likes this.
  10. Yanglovess

    Yanglovess

    Joined:
    Aug 1, 2017
    Posts:
    1
    Hi, thanks for your great work, I wonder if this works for obj file which don't have mtl file?
    Thanks.
     
  11. wphyo_midmark

    wphyo_midmark

    Joined:
    Jun 28, 2017
    Posts:
    1
    For OBJ files that doesnt have mtl files... all I had to was add an empty string to materialNames in LoadOBJFile function.

    Code (CSharp):
    1.  
    2. if (objectNames.Count == 0)
    3.     objectNames.Add("default");
    4. materialNames.Add(""); //just add this line
    5.  
     
  12. TheBored

    TheBored

    Joined:
    Aug 23, 2014
    Posts:
    10
    Hi @aaro4130 - do you have the source code anywhere public that can take contributions? There are some changes I would like to make that would benefit everyone - including some bug fixes from this thread. If the source is on GH I'd be happy to submit a PR.
     
  13. raptcha

    raptcha

    Joined:
    Jan 16, 2017
    Posts:
    4
    Hey @aaro4130,
    I'm trying to import a OBJ in runtime and build a navmesh using the new navmeshsurface component from unity 5.6. The OBJ importing part is working great. For the models which are not imported during runtime, the navmesh generation works just fine, but for the ones imported during runtime using your plugin, the navmesh is just not building anything. Any ideas??

    Thanks
     
  14. Rajawat

    Rajawat

    Joined:
    Oct 1, 2016
    Posts:
    25
    Should it not be
    Code (CSharp):
    1. const int MAX_VERTICES_PER_MESH = 64990;
    ?
    Why it is multiplied by 3 ?
     
  15. oLDo

    oLDo

    Joined:
    Mar 14, 2017
    Posts:
    53
    Hi.

    I like this solution for loading OBJ models. But I have some issue with TextureLoader. I'm trying to load tga but this error shows up:

    Can you help me?

    I was test it with this model https://free3d.com/3d-model/german-panzer-ww2-ausf-b-quotkingtigerquot-19449.html
     
  16. vuluongthanh

    vuluongthanh

    Joined:
    Nov 23, 2013
    Posts:
    16
    It my bad code when i get wrong idea at the begining. Sorry. if you change it, you need to change this line too "faceCountDict[newName] > (MAX_VERTICLES_PER_MESH / 3)"
     
  17. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395


    Unity is bringing 32 bit mesh indices into Unity 2017.3?, which means we won't have to do this splitting stuff anymore :)
     
    Last edited: Dec 16, 2017
    oLDo likes this.
  18. pedroberni

    pedroberni

    Joined:
    Oct 26, 2017
    Posts:
    8
    Hi, I`m new to unity. Trying to use this script, most of objects I import in the editor, in GameObjects, does not appear.
    Even simple models like a cube OBJ.
    I see in the inspector that they show material size 0, even editing this sometimes doenst make the object appear, they just look like a empty object. Could someone help me please?
     
  19. cjmcassar

    cjmcassar

    Joined:
    Sep 5, 2017
    Posts:
    1
    The script runs fine during running but post-build the upload function doesn't seem to work... anyone have any suggestions?
     
  20. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    Include the "Standard (Specular Shader)" in always included shaders. Note that this will increase build time.
     
  21. neosca

    neosca

    Joined:
    Jul 1, 2014
    Posts:
    8
    How do I load an obj file from a web url directly instead of local?
     
  22. foobraco

    foobraco

    Joined:
    Oct 20, 2012
    Posts:
    7
    Hi @aaro4130 I'm having the same issue with the vertices being over 65k, could you please help me to sort it out?
     
  23. Deleted User

    Deleted User

    Guest

    Can I write custom type like not only obj just example bsp is for game loader it is like model and can I read whole cs of ObjImporter ? And can bsp detect limit 65535 than it will load into sub mesh like obj splitters? Thanks!
     
  24. JPLNO

    JPLNO

    Joined:
    Jul 6, 2017
    Posts:
    1
    I'm using Unity 2017.2.1f1 and there is no increased limit of vertices ! Stay stuck at 65K.
    Where do you find this information ?
     
  25. abhi10243

    abhi10243

    Joined:
    Jan 3, 2018
    Posts:
    2
    hey buddy I'm new in unity and may be dont know hoe to use this.
    I have an problem during run time in my console which is below so if you have time then plz take a look

    ArgumentOutOfRangeException: Argument is out of range.
    Parameter name: index
    System.Collections.Generic.List`1[UnityEngine.Vector3].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
    OBJLoader.LoadOBJFile (System.String fn) (at Assets/OBJImport/OBJLoader.cs:297)
    MyTest.OnGUI () (at Assets/VoidARDemo/Scripts/MyTest.cs:40)

    thnks in advance
     
  26. abhi10243

    abhi10243

    Joined:
    Jan 3, 2018
    Posts:
    2
    any tutorial about that becz I'm not able to figure it out how to use it
     
  27. UDN_4adacac2-07fb-4baf-82ea-a1d498011919

    UDN_4adacac2-07fb-4baf-82ea-a1d498011919

    Joined:
    Oct 3, 2017
    Posts:
    1
    Help please, modelka is unloaded without textures, how to fix it? What to do? I need urgent help. I'll attach the screenshots from the code, and the result
     

    Attached Files:

  28. gambr

    gambr

    Joined:
    Oct 13, 2017
    Posts:
    97
    I have the same issue but I don't understand how to solve it.
     
  29. gambr

    gambr

    Joined:
    Oct 13, 2017
    Posts:
    97
    Solved, but that's crazy! Why, why whyyyyy ... Unity is so stupidly complicated? Why should I have to add such a shader for the stand-alone player while it is working in the editor??? It MUST work the same without modifications!
     
  30. nguyenjt

    nguyenjt

    Joined:
    Feb 24, 2018
    Posts:
    1
    Hi there, any insight on how to solve it? I'm a bit stuck myself.
     
  31. gambr

    gambr

    Joined:
    Oct 13, 2017
    Posts:
    97
    Edit -> Project Settings -> Graphics
    Then From Inspector Tab search for "Always Included Shaders" (please see attached image). Add 1 to the Size field and then select "Standard (Specular setup) for the new field.
     

    Attached Files:

    • temp.png
      temp.png
      File size:
      23.7 KB
      Views:
      432
  32. Deleted User

    Deleted User

    Guest

    Hello Unity3D-developers can you help about struct of WaveFrontLoader.cs I really want know Why does it not show in OpenTK ( Sorry it is not related to Unity but I don't know if they know how does it parse with wavefront without material ) Thank you!
     
  33. Y76_Unity

    Y76_Unity

    Joined:
    Jan 29, 2018
    Posts:
    28
    widow freeze when the OBJ file is more than 5 MB ?
    What to do with window freezing ?
     
  34. piwniczne

    piwniczne

    Joined:
    May 4, 2018
    Posts:
    1
    Hi,

    first of all: thanks for loader!

    I've got some problem with loading mtl file.
    Inside your code I saw chaking for some type of data insidle mtl file: map_Kd, map_Bump etc.
    But my mtl file also uses types like this: map_Ka, map_refl which are not mapped.

    How could I know how to add code that will map them?
    It's killing bug since lots of OBJ doens't work without this.

    thanks.
     
  35. akhtarsalmaan2

    akhtarsalmaan2

    Joined:
    May 6, 2018
    Posts:
    2
    Hi i would like how to use this
     
  36. SimRuJ

    SimRuJ

    Joined:
    Apr 7, 2016
    Posts:
    140
    Hi!

    Do you still support this asset?
    I tried to load a couple of my meshes and starting my app takes a bit longer than usual, so it is definitely doing something but in the end it won't display anything.
    I've tried it with a couple of meshes (from 800kb to 4mb) but no luck with any of them. They're all ".obj" files with both an ".mtl" and a ".jpg" file with the same name (so: mymesh.obj, mymesh.mtl, mymesh.jpg) in the same folder.

    Do yo have to do anything else other than:
    Code (CSharp):
    1. String path = "myfolder" + Path.DirectorySeparatorChar + "objfilename" + ".obj";
    2. GameObject myObj = OBJLoader.LoadOBJFile(path);
    ?

    I already tried giving it a new material but it didn't work either:
    Code (CSharp):
    1. Material mat = new Material(Shader.Find("Hidden/Internal-Colored")) { color = new Color(0,0,1) };
    2. myObj.GetComponent<MeshRenderer>().material = mat;
    Unity: 2017.3.1f1 / C#


    Edit:
    I also just tried importing different meshes from the editor and it said something like "OBJ load took 1163ms" every time. There's an entry in the hierarchy and there are x/y/z axis but the actual object isn't displayed, neither in the "scene" tab nor when the game was running ("game" tab) - it's simply invisible.
    The material size is set to "0" automatically, so I set it to "1" and simply added the "Default Skybox" material to it but that didn't help either.
     
    Last edited: May 17, 2018
  37. kuldeepsinghthakur

    kuldeepsinghthakur

    Joined:
    Jul 10, 2018
    Posts:
    2
    Hi ,
    Thank you for giving this wonderful asset. while rendering obj file into scene at run time it work good. but I want to know is it possible to attach script on some material of obj .
     
  38. DarthHawk13

    DarthHawk13

    Joined:
    Feb 24, 2016
    Posts:
    16
    I was having an issue but restarting the computer fixed it. The problem was it was working sometimes in importing the 3d model during runtime and the rest of the time the app was logging the error it could not access the directory. Works good. Thanks :)
     
    Last edited: Sep 16, 2018
  39. hks_adohkd

    hks_adohkd

    Joined:
    Sep 7, 2018
    Posts:
    12
    Hi @aaro4130
    Your asset is more than great thanks a lot!
    but there is a problem that I don't know if it's from your asset.
    the object that I imported with its mtl file and dds textures is white although they are imported successfully
    here is a link to a picture that demonstrate the problem link
     
  40. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    Next update will bring major speed improvements.
    upload_2019-1-3_9-58-26.png upload_2019-1-3_9-58-35.png upload_2019-1-3_9-58-50.png upload_2019-1-3_9-59-28.png

    Other neat things
    -Added support to load OBJ and MTL files from Streams, so you can load your content via WWW, StreamingAssets, etc.
    -Brand new texture loader, with improved TGA support (RLE compression now supported)
    -Adds support for negative indices, something that broke the old version sometimes
    -Will be licensed under MIT in the future
    -NGon support, no more holes in the model caused by missing ngon support.
    -Totally new code :)
    -32 bit index support
    -MTL no longer required

    Rewritten from scratch, will submit to the asset store soon
     
    Last edited: Jan 4, 2019
    carking1996 and oLDo like this.
  41. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    Still improving that ratio btw :)

    upload_2019-1-3_21-14-0.png
     
    Last edited: Jan 4, 2019
  42. carking1996

    carking1996

    Joined:
    Jun 15, 2010
    Posts:
    2,563
    Huge improvements, good stuff.
     
  43. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    V2.0 preview released.

    Download: https://forum.unity.com/attachments/objimportv2-preview-zip.353863/
    Changelog: 2 posts up

    Hopefully you see huge speed improvements, and better imports :)

    ---------------------------------------------------
    upload_2019-1-4_19-58-7.png
    ---------------------------------------------------
    map_Ka is now supported in the v2.0 preview

    The mtl reading code has been rewritten. Try again now if this asset is still applicable to you, as there are improvments in this area :).
     
    Last edited: Jan 5, 2019
    TerraUnity likes this.
  44. mmaethner

    mmaethner

    Joined:
    Jan 8, 2018
    Posts:
    2
    Hey @aar4010
    I'm testing your importer and it hast drastically improved with your update. Your importer only supports the use of either the 'g' or the 'o' keyword, resulting in empty objects if both are set. I would have expected that meshes get grouped under the 'g' keyword, which is not the case. I then tested your script by making it ignore the 'o' keyword and only use 'g'. The resulting mesh is then missing most of its vertices. But this only occurs, if the same groups inside of my .obj file appear multiple times on different parts of the file. E.g:
    Code (CSharp):
    1. g Trees
    2. o tree_01
    3. usemtl bark
    4. v ...
    5. f ...
    6. usemtl leaves
    7. [...]
    8. g Terrain
    9. usemtl surface
    10. v...
    11. f...
    12. [...]
    13. g Trees
    14. o tree_02
    15. usemtl bark
    16. [...]
    17. usemtl leaves
    18. [...]
    Using a sorted .obj file (e.g. all 'Tree' groups combined to one 'Tree' group) the import works fine.
    Do you have any idea what could be the cause of this?

    I also found out, that you need to set the index format of your mesh before you set the submesh count. If you are going to switch from the default 16 to 32 bit indexing, the submesh count of your mesh will get set to 1, causing exceptions on larger .obj files.

    old:
    Code (CSharp):
    1. submesh = 0;
    2. var msh = new Mesh() { name = _name, subMeshCount = _materialIndices.Count };
    3. msh.indexFormat = (_vertices.Count > 65535) ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16;
    4. // if true, msh.submeshcount will be 1 from now on
    fix:
    Code (CSharp):
    1. var msh = new Mesh() {
    2.             name = _name,
    3.             indexFormat = (_vertices.Count > 65535) ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16,
    4.         subMeshCount = _materialIndices.Count
    5.         };
    I hope I was able to explain my problem and you can help me out.

    Regards
     
  45. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    Whoops, good catch!

    The g/o being treated the same seems to be pretty standard with 3D packages that I've used. I think it's because some exporters either do o, or g, and not both, then software gets created that treats these as the same thing.

    Thanks to "Pulni", which I met from the GDL Discord, there have been even more speed improvements, and GC improvements as well, so you should see that with the next version :)
     
  46. mmaethner

    mmaethner

    Joined:
    Jan 8, 2018
    Posts:
    2
    Sadly I'm stuck with my file formatting. My obj's are generated from an external application. But I managed to find the error. With your SetMaterial function you make sure that you write faces to a separate list per material.

    Your code:
    Code (CSharp):
    1. public void SetMaterial(string name)
    2.     {
    3.         if (!_materialIndices.TryGetValue(_name, out _currentIndexList))
    4.         {
    5.             _currentIndexList = new List<int>();
    6.             _materialIndices[name] = _currentIndexList;
    7.         }
    8.     }
    I assume this was an autocomplete error, but you use the private field _name for the name of the object, instead of the name parameter.

    Fixed code:

    Code (CSharp):
    1. public void SetMaterial(string name)
    2.     {
    3.         if (!_materialIndices.TryGetValue(name, out _currentIndexList))
    4.         {
    5.             _currentIndexList = new List<int>();
    6.             _materialIndices[name] = _currentIndexList;
    7.         }
    8.     }

    This explains why your importer works for split by material but not by group.
     
  47. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    Ugh, yep, that's an autocomplete error! Thanks for catching that one lol.
     
  48. gambr

    gambr

    Joined:
    Oct 13, 2017
    Posts:
    97
    Some unit testing will prevent such errors.
     
  49. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    Submitted a bugfix and speed improvement update to the asset store. Pending review.
     
    Gerard_Slee likes this.
  50. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    395
    2.01 should be live!