I keep getting context is invalid error, when trying to merge all meshes in the scene
### sources:
### - base code generated by ChatGPT.
### - merging code from: https://blender.stackexchange.com/questions/13986/how-to-join-objects-with-python
import bpy
import os
# Set the directory containing the .3ds files
input_folder = "C:\Database\ModelDB\furniture"
output_folder = "C:\Database\ModelDB\furniture"
# Ensure the output directory exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Loop through all the .3ds files in the input folder
for file_name in os.listdir(input_folder):
if file_name.endswith(".3ds"):
# Full path to the .3ds file
input_file = os.path.join(input_folder, file_name)
# Define output .fbx file path
output_file = os.path.join(output_folder, file_name.replace(".3ds", ".fbx"))
# Clear any previous data in Blender
bpy.ops.wm.read_homefile(use_empty=True)
# Import the .3ds file
bpy.ops.import_scene.autodesk_3ds(filepath=input_file)
# Select and join all objects
bpy.ops.object.select_all(action='DESELECT')
count = 0
# obs = []
for ob in bpy.context.scene.objects:
if ob.type == 'MESH':
# obs.append(ob)
ob.select_set(state=True)
bpy.context.view_layer.objects.active = ob
count += 1
if (count > 1):
# with bpy.context.temp_override(active_object=obs[0], selected_objects=obs):
bpy.ops.object.join()
# Export to .fbx
bpy.ops.export_scene.fbx(filepath=output_file, use_selection=False)
print(f"Converted {input_file} to {output_file}")
print("Conversion completed.")
The line that crashes is bpy.ops.object.join()
with the following error
RuntimeError: Operator bpy.ops.object.join.poll() failed, context is incorrect
I also tried the commented lines with the ops array, but I can't get it to work. When I hit Ctrl+J in the scene window, at the point where the script crashes, it merges correctly and the objects seem to be selected correctly (All objects are selected and I have an active obejct).
What am I doing wrong?
EDIT: running bpy.ops.object.join()
from the python console after the crash also works. Is this some kind of async error, that the selection or something like that hasn't finished yet??