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

Selective import of blender models

Discussion in 'Asset Importing & Exporting' started by grobonom, Oct 23, 2018.

  1. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    Hey guys :)

    I wonder wether there's a way to import blender objects selectively.

    I mean, in my Blender scene i got 'The_Object' i want to import and all other objects that i dont want to import in unity but that are usefull for... AO/lighting bake-in-blender....

    I thought about blender layers ( simple and efficient way to show/hide things of a scene in blender ) but they are ALL imported in unity. ( would have been nice that unity exclude layer 19 from import. i guess it would just a conditionnal if(object_layer==19) discard_object_import(); )

    anybody has a clue/trick/tutorial/import_script for this please ?

    this would be.... GREAAAAT !!!

    ;)

    happy Unitying !
     
  2. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    hmmm okay i guess without any answer that it's not possible :/

    I tried to make separate blend files and link them in blender but unity also imports linked objects :((

    however, if someone have an idea or a technique for selective model import from blender files, i'd be fond of it ;)

    happy unitying !!!
     
  3. steego

    steego

    Joined:
    Jul 15, 2010
    Posts:
    968
    Are you using the .blend file directly in Unity? It is generally better to export as fbx from Blender, there is an option when you export to only save selected objects that you can use.
     
    _GimbalLock_ likes this.
  4. Ne0mega

    Ne0mega

    Joined:
    Feb 18, 2018
    Posts:
    702
    Use the FBX exporter.

    Select the objects you want to export.

    File --> Export --> FBX

    Choose MAIN, tick "selected Objects", change Apply Scale to "FBX all"

    choose your location, and click "export FBX" in the upper right.
     
  5. pitibonom

    pitibonom

    Joined:
    Aug 17, 2010
    Posts:
    188
    Seems lots of ppl don't use blender <---> unity for saying export as this, never use that.... XD lol

    WORKFLOW is the master word when creating 3D. and the right way of doing things is to make then as smooth as possible. Imagine if every 10 meters, you should stop your car, get outta it, close the doors, wait 17 seconds, open the doors get into it, start engine, make 10 more meters and redo the whole S*** ? :D lol

    hopefully U3D team and Blender team did things in a much more intelligent way ( than the common one: NEVER USE BLENDS... lol )

    There's a lil script written in python bundled with unity. it is called
    Unity-BlenderToFBX.py
    and is located on a win machine
    in programfiles/unity/hub/editor/*theVersionYouUse*/data/tools

    you who ( with no doubt ) write some lil scripts in unity will be aware of what to do for editing this script and change it for your specific needs in importing your work into unity.

    for example, i model with blender and create some light/shadow/mist/etc meshes that are used in texture bakes, but that i NEVER want in unity. I just don't want to see them in unity as they are annoying and useless. but i need them in blender....
    imagine you can put a thing in blender saying 'i dont want this in unity'....
    YES YOU CAN !!!

    lets assume that you exclude objects in unity from a char in their name
    in your blend you got 2 objects:
    one named cube
    and
    one named _sphere

    the '_' will be the object excluder in unity3D import.

    for this you just have to change the
    Unity-BlenderToFBX.py
    at the end and replace:

    # 2.59 and later

    kwargs = io_scene_fbx.export_fbx.defaults_unity3d()
    io_scene_fbx.export_fbx.save(FakeOp(), bpy.context, filepath=outfile, **kwargs)
    # HQ normals are not supported in the current exporter

    print("Finished blender to FBX conversion " + outfile)


    with :


    # 2.59 and later
    # HACK SELECTIVE BLENDER IMPORT
    for obj in bpy.data.objects:
    obj.select = False if obj.name[0] in '_.' else True
    #end HACK

    kwargs = io_scene_fbx.export_fbx.defaults_unity3d()
    # HACK SELECTIVE BLENDER IMPORT
    kwargs["use_selection"] = True
    #end HACK
    io_scene_fbx.export_fbx.save(FakeOp(), bpy.context, filepath=outfile, **kwargs)
    # HQ normals are not supported in the current exporter

    print("Finished blender to FBX conversion " + outfile)


    and voila :) in unity you'll only retrieve the cube ! the sphere will be discarded !

    happy blending and unitying !!!
     
    mivasiliauskas and Siccity like this.
  6. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    It appears this don't work properly anymore in U2019 :/

    Anyone knowing python could help me please ?
     
    Last edited: May 21, 2019
  7. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    finally i made it work with this:
    Code (CSharp):
    1. import bpy.ops
    2. import bpy
    3. minor = bpy.app.version[1]
    4. blender280 = minor >= 80
    5. if not blender280:
    6.         try:
    7.             import io_scene_fbx.export_fbx
    8.         except:
    9.             print('error: io_scene_fbx.export_fbx not found.')
    10.             # This might need to be bpy.Quit()
    11.             raise
    12. # Find the Blender output file
    13. import os
    14. outfile = os.getenv("UNITY_BLENDER_EXPORTER_OUTPUT_FILE")
    15. # Do the conversion
    16. print("Starting blender to FBX conversion " + outfile)
    17. if blender280:
    18.     bpy.ops.export_scene.fbx(filepath=outfile,
    19.         check_existing=False,
    20.         use_selection=False,
    21.         use_active_collection=False,
    22.         object_types= {'ARMATURE','CAMERA','LIGHT','MESH','EMPTY'},
    23.         use_mesh_modifiers=True,
    24.         mesh_smooth_type='OFF',
    25.         use_custom_props=True,
    26.         apply_scale_options='FBX_SCALE_ALL'
    27.     )
    28. else:
    29.     # blender 2.58 or newer
    30.     import math
    31.     from mathutils import Matrix
    32.     # -90 degrees
    33.     mtx4_x90n = Matrix.Rotation(-math.pi / 2.0, 4, 'X')
    34.     print("moo")
    35.     class FakeOp:
    36.         def report(self, tp, msg):
    37.             print("%s: %s" % (tp, msg))
    38.     exportObjects = ['ARMATURE', 'EMPTY', 'MESH']
    39.     minorVersion = bpy.app.version[1];
    40.     if minorVersion <= 58:
    41.         # 2.58
    42.         io_scene_fbx.export_fbx.save(FakeOp(), bpy.context, filepath=outfile,
    43.             global_matrix=mtx4_x90n,
    44.             use_selection=False,
    45.             object_types=exportObjects,
    46.             mesh_apply_modifiers=True,
    47.             ANIM_ENABLE=True,
    48.             ANIM_OPTIMIZE=False,
    49.             ANIM_OPTIMIZE_PRECISSION=6,
    50.             ANIM_ACTION_ALL=True,
    51.             batch_mode='OFF',
    52.             BATCH_OWN_DIR=False)
    53.     else:
    54.         # 2.59 and later
    55.         # deselect everything to close edit / pose mode etc.
    56.         bpy.context.scene.objects.active = None
    57.  
    58.         # activate all layers
    59.         for i in range(0, 20):
    60.              bpy.data.scenes[0].layers[i] = True;
    61.            
    62.         # parse objects and disable those with underscore or dot
    63.         for obj in bpy.data.objects:
    64.             obj.select = False if obj.name[0] in '_.' else True
    65.         kwargs = io_scene_fbx.export_fbx.defaults_unity3d()
    66.         kwargs["use_selection"] = True
    67.         io_scene_fbx.export_fbx.save(FakeOp(), bpy.context, filepath=outfile, **kwargs)
    68.     # HQ normals are not supported in the current exporter
    69.  
    70.  
    71.  
    72. print("Finished blender to FBX conversion " + outfile)
    73.  
    happy unitying :)
     
    Lahcene likes this.
  8. spiraloid

    spiraloid

    Joined:
    Aug 11, 2015
    Posts:
    7
    I found that making a collection called export and deactivating all the other collections gave me better control btw.
     
    Siccity and gwelkind like this.
  9. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    sorry i dunno what are collections :/
    but am happy if this works for you :)

    happy unitying !
     
  10. Alesk

    Alesk

    Joined:
    Jul 15, 2010
    Posts:
    339
    Hi !

    Is there any way to get access to the generated FBX file ?
     
  11. gwelkind

    gwelkind

    Joined:
    Sep 16, 2015
    Posts:
    65
    Just want to reemphasize what spiraloid said, this should be the go-to solution for anyone solving in 2021.

    Just disable (uncheck) any objects you don't want to take with you, save, and unity will magically update.
    If you absolutely can't do this, link the object you need into a new file.
     
  12. grobonom

    grobonom

    Joined:
    Jun 23, 2018
    Posts:
    335
    Hi all :)

    Note that since blender 3.0.0+ this script won't work.
    Here's the version with complete blender version testing...
    Code (CSharp):
    1. import bpy.ops
    2. import bpy
    3. major = bpy.app.version[0]
    4. minor = bpy.app.version[1]
    5. underminor = bpy.app.version[2]
    6. #blender280 = minor >= 80
    7. #if not blender280:
    8. #        try:
    9. #            import io_scene_fbx.export_fbx
    10. #        except:
    11. #            print('error: io_scene_fbx.export_fbx not found.')
    12.             # This might need to be bpy.Quit()
    13. #            raise
    14. # Find the Blender output file
    15. import os
    16. outfile = os.getenv("UNITY_BLENDER_EXPORTER_OUTPUT_FILE")
    17. # Do the conversion
    18. print("Starting blender to FBX conversion " + outfile)
    19. # Blender versions tests come here:
    20. if (major == 2 and minor >= 80) or (major >= 3 and minor >= 0): # blender > 2.79 ( including 3.0+ )
    21.  
    22.     # ---> changes for B2.9 to U3D 18-10-2020
    23.     # blender 2.8 or newer
    24.  
    25.  
    26.     # 1st of all show/activate all collections
    27.     for coll in bpy.data.collections:
    28.         coll.hide_render = False
    29.         coll.hide_select = False
    30.  
    31.  
    32.     # deselect everything
    33.     bpy.ops.object.select_all(action='DESELECT')
    34.    
    35.     # then parse all objects list.
    36.     # activate the current one and only inactivate it if is has a '_' or '.' ath the start of its name.
    37.     # also inactivate it if it's a linked object :-)
    38.     for obj in bpy.data.objects:
    39.         obj.select_set(True)
    40.         if obj.name[0] in '_.':
    41.             obj.select_set(False)
    42.         the_obj = bpy.data.objects[obj.name]
    43.         if the_obj.library != None:
    44.             obj.select_set(False)
    45.  
    46.                
    47.     bpy.ops.export_scene.fbx(filepath=outfile,
    48.         check_existing=False,
    49.         use_selection=True,  #use_selection=False,
    50.         use_active_collection=False,
    51.         object_types= {'ARMATURE','MESH'}, #object_types= {'ARMATURE','CAMERA','LIGHT','MESH','EMPTY'},
    52.         use_mesh_modifiers=True,
    53.         mesh_smooth_type='OFF',
    54.         use_custom_props=True,
    55.         apply_scale_options='FBX_SCALE_ALL',
    56.         use_space_transform=False, # modifs recentes pour reorientation dans unity ( need bake axis conversion at import )
    57.         axis_forward='-Y',  # modifs recentes pour reorientation dans unity ( need bake axis conversion at import )
    58.         axis_up='Z'  # modifs recentes pour reorientation dans unity ( need bake axis conversion at import )
    59.     )
    60.     # <--- changes for B2.9 tu U3D 18-10-2020
    61.    
    62. else:
    63.  
    64.     # blender 2.79 or older
    65.     import math
    66.     from mathutils import Matrix
    67.     # -90 degrees
    68.     mtx4_x90n = Matrix.Rotation(-math.pi / 2.0, 4, 'X')
    69.     class FakeOp:
    70.         def report(self, tp, msg):
    71.             print("%s: %s" % (tp, msg))
    72.     exportObjects = ['ARMATURE', 'EMPTY', 'MESH']
    73.     if minor <= 58:
    74.         # 2.58
    75.         io_scene_fbx.export_fbx.save(FakeOp(), bpy.context, filepath=outfile,
    76.             global_matrix=mtx4_x90n,
    77.             use_selection=False,
    78.             object_types=exportObjects,
    79.             mesh_apply_modifiers=True,
    80.             ANIM_ENABLE=True,
    81.             ANIM_OPTIMIZE=False,
    82.             ANIM_OPTIMIZE_PRECISSION=6,
    83.             ANIM_ACTION_ALL=True,
    84.             batch_mode='OFzF',
    85.             BATCH_OWN_DIR=False)
    86.     else:
    87.         # 2.59 and later
    88.         # deselect everything to close edit / pose mode etc.
    89.         bpy.context.scene.objects.active = None
    90.  
    91.         # activate all layers
    92.         for i in range(0, 20):
    93.              bpy.data.scenes[0].layers[i] = True
    94.            
    95.         # parse objects and disable those with underscore or dot and also those that are linked from othe files...
    96.  
    97.         for obj in bpy.data.objects:
    98.             obj.select = True
    99.             if obj.name[0] in '_.':
    100.                 obj.select = False
    101.             the_obj = bpy.data.objects[obj.name]
    102.             if the_obj.library != None:
    103.                 obj.select = False
    104.         kwargs = io_scene_fbx.export_fbx.defaults_unity3d()
    105.         kwargs["use_selection"] = True
    106.         io_scene_fbx.export_fbx.save(FakeOp(), bpy.context, filepath=outfile, **kwargs)
    107.     # HQ normals are not supported in the current exporter
    108.  
    109.  
    110.  
    111. print("Finished blender to FBX conversion " + outfile)
    112.  
    113.  
    Note that it is adapted to my needs ( with linked objects and objects starting with a _ or . discarded from import...

    Happy unitying !
     
    sbat likes this.