先日はBlender内ですべてのシーンコレクション内のカメラの数を取得していきました。
今回は非選択のカメラオブジェクトを削除する処理を実装します。
〇環境
・Blender4.1
・Windows11PC
〇選択されていないカメラオブジェクトの取得
今回は選択されていないカメラオブジェクト名を取得します。
コードは次のようになります。
肝としてはnon_selected_camerasを追加して選択されていないカメラオブジェクトを
import bpy
def get_non_selected_cameras():
# 選択されているカメラを取得
selected_camera = bpy.context.scene.camera
# 非選択カメラの名前を格納するリスト
non_selected_cameras = []
# すべてのコレクションを走査
for collection in bpy.data.collections:
# コレクション内のオブジェクトを調べる
for obj in collection.objects:
# オブジェクトがカメラで、かつ選択されているカメラでない場合
if obj.type == 'CAMERA' and obj != selected_camera:
non_selected_cameras.append(obj.name)
# サブコレクションを走査する場合(Blender 3.0以降)
for sub_collection in collection.children:
for obj in sub_collection.objects:
if obj.type == 'CAMERA' and obj != selected_camera:
non_selected_cameras.append(obj.name)
return non_selected_cameras
# 非選択カメラの名前を取得して出力
non_selected_camera_names = get_non_selected_cameras()
print("選択されていないカメラ名:")
for name in non_selected_camera_names:
print(name)

またコードの最後にdelete_non_selected_cameras()を加えることで非選択オブジェクトの削除が行われ、選択中のカメラのみが残るようになります。
本日は以上です。
次回はGUIを作成して使いやすくしていきます。
〇コード全文
import bpy
def delete_non_selected_cameras():
# 選択されているカメラを取得
selected_camera = bpy.context.scene.camera
# 削除予定のカメラを一時的に保持するリスト
cameras_to_delete = []
# すべてのコレクションを走査
for collection in bpy.data.collections:
# コレクション内のオブジェクトを調べる
for obj in collection.objects:
# オブジェクトがカメラで、かつ選択されているカメラでない場合
if obj.type == 'CAMERA' and obj != selected_camera:
cameras_to_delete.append(obj)
# サブコレクションを走査する場合(Blender 3.0以降)
for sub_collection in collection.children:
for obj in sub_collection.objects:
if obj.type == 'CAMERA' and obj != selected_camera:
cameras_to_delete.append(obj)
# 収集したカメラオブジェクトを削除
for camera in cameras_to_delete:
bpy.data.objects.remove(camera, do_unlink=True)
print(f"削除したカメラ: {camera.name}")
# 非選択カメラを削除
delete_non_selected_cameras()