Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created April 22, 2022 02:09
Show Gist options
  • Save jordanorelli/8a40dd928a2788e57629017a50b49238 to your computer and use it in GitHub Desktop.
Save jordanorelli/8a40dd928a2788e57629017a50b49238 to your computer and use it in GitHub Desktop.
static mesh exporter for blender to unity
from math import pi
import bpy
import os
import copy
# export to blend file location
dirname = os.path.dirname
basedir = dirname(dirname(dirname(bpy.data.filepath)))
export_dir = os.path.join(basedir, "Assets", "Models")
print("saving to " + export_dir)
if not export_dir:
raise Exception("Blend file is not saved")
view_layer = bpy.context.view_layer
obj_active = view_layer.objects.active
original_selection = bpy.context.selected_objects
print(f"exporting {len(original_selection)} objects")
bpy.ops.object.select_all(action='DESELECT')
for obj in original_selection:
name = bpy.path.clean_name(obj.name)
print(f"exporting {obj.name} as {name}")
# select the one object
obj.select_set(True)
original_location = copy.copy(obj.location)
obj.location = (0, 0, 0)
original_rotation = copy.copy(obj.rotation_euler)
# apply an odd rotation
obj.rotation_euler = (-pi/2, pi, 0)
# scale this fucker
obj.scale = (100, 100, 100)
# apply our transforms
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True, properties=False)
# actually don't fucking understand why this works
obj.rotation_euler = (pi/2, 0, 0)
# some exporters only use the active object
view_layer.objects.active = obj
fn = os.path.join(export_dir, name)
print(f"exporting {name} to {fn}.fbx")
# export the fbx with the weird rotation thing
try:
bpy.ops.export_scene.fbx(
filepath=fn + ".fbx",
use_selection=True,
axis_forward='Z',
axis_up='Y',
global_scale=0.01,
apply_unit_scale=True)
except Exception:
print(f"failed to export {name}")
# apply the second rotation to undo the first one
# bpy.ops.object.transform_apply(location=False, rotation=True, scale=True, properties=False)
obj.location = original_location
obj.rotation_euler = (pi/2, 0, pi)
obj.scale = (0.01, 0.01, 0.01)
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True, properties=False)
obj.select_set(False)
print(f"written: {fn}.fbx")
view_layer.objects.active = obj_active
for obj in original_selection:
obj.select_set(True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment