Blender Python スクリプト 文字列入力フィールドをプロパティシェルフに追加し、入力された文字列をコマンドとして実行する exec関数を利用して改善。
- # 文字列入力フィールドをプロパティシェルフに追加し、入力された文字列をコマンドとして実行する
- import bpy
- from bpy.props import *
- def initSceneProperties(scn):
- # StringProperty デフォルトでは円柱追加のコマンドが設定されている
- bpy.types.Scene.MyString = StringProperty(
- name = "String")
- scn['MyString'] = "bpy.ops.mesh.primitive_cylinder_add()"
- return
- initSceneProperties(bpy.context.scene)
- # パネル
- class UIPanel(bpy.types.Panel):
- bl_label = "Property panel"
- bl_space_type = "VIEW_3D"
- bl_region_type = "UI"
- def draw(self, context):
- layout = self.layout
- scn = context.scene
- # 文字列入力
- layout.prop(scn, 'MyString')
- layout.operator("object.simple_operator_x")
- # コマンド
- class SimpleOperator_x(bpy.types.Operator):
- """Tooltip"""
- bl_idname = "object.simple_operator_x"
- bl_label = "Simple Object Operator"
- def execute(self, context):
- # 成功すれば以下のコマンドが実行され、円柱が追加される
- # bpy.ops.mesh.primitive_cylinder_add()
- # そのままやってみる
- # context.scene.MyString
- scn = context.scene
- exec(scn.MyString)
- # print してみる
- # print(bpy.types.Scene.MyString)
- # コンソールに入力してみる(よくわからんエラーが出る
- # bpy.ops.console.execute(bpy.types.Scene.MyString)
- return {'FINISHED'}
- # Registration
- bpy.utils.register_module(__name__)