Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Import every FBX in a directory into an individual collection.
- Run this script from Blender 5.2's Scripting workspace. Each FBX is imported
- using the native FBX importer defaults, then its imported objects are moved to
- a collection named after the FBX and parented to a ``<FBX name> Null`` empty.
- """
- from pathlib import Path
- import bpy
- FBX_DIRECTORY = Path(r"K:\Videos\Weapons\Starship Troopers Guns\All FBXs")
- def get_or_create_collection(name: str) -> bpy.types.Collection:
- """Return a scene-linked collection with *name*."""
- collection = bpy.data.collections.get(name)
- if collection is None:
- collection = bpy.data.collections.new(name)
- bpy.context.scene.collection.children.link(collection)
- return collection
- def move_to_collection(obj: bpy.types.Object, collection: bpy.types.Collection) -> None:
- """Make *collection* the object's only collection."""
- for current_collection in tuple(obj.users_collection):
- current_collection.objects.unlink(obj)
- collection.objects.link(obj)
- def import_fbx(fbx_path: Path) -> None:
- """Import one FBX and organize every object created by that import."""
- objects_before = set(bpy.data.objects)
- # Supplying only filepath deliberately uses Blender 5.2's native importer
- # default settings for every FBX.
- bpy.ops.wm.fbx_import(filepath=str(fbx_path))
- imported_objects = [obj for obj in bpy.data.objects if obj not in objects_before]
- if not imported_objects:
- print(f"No objects were imported from: {fbx_path}")
- return
- asset_name = fbx_path.stem
- collection = get_or_create_collection(asset_name)
- empty = bpy.data.objects.new(f"{asset_name} Null", None)
- empty.empty_display_type = 'PLAIN_AXES'
- collection.objects.link(empty)
- for obj in imported_objects:
- move_to_collection(obj, collection)
- # The empty is at the world origin, so this preserves imported transforms
- # while making every imported object a child of the asset empty.
- obj.parent = empty
- obj.matrix_parent_inverse = empty.matrix_world.inverted()
- print(f"Imported {fbx_path.name}: {len(imported_objects)} objects -> {collection.name}")
- def main() -> None:
- if not FBX_DIRECTORY.is_dir():
- raise FileNotFoundError(f"FBX directory does not exist: {FBX_DIRECTORY}")
- fbx_files = sorted(
- (path for path in FBX_DIRECTORY.iterdir() if path.is_file() and path.suffix.lower() == ".fbx"),
- key=lambda path: path.name.casefold(),
- )
- if not fbx_files:
- print(f"No FBX files found in: {FBX_DIRECTORY}")
- return
- for fbx_path in fbx_files:
- import_fbx(fbx_path)
- print(f"Finished importing {len(fbx_files)} FBX file(s).")
- if __name__ == "__main__":
- main()
Advertisement