blender/blender python

랜덤값

monstro 2025. 8. 13. 11:48
728x90
반응형

- 개요

랜덤한 정수값을 생성하고 생성한 값에 따라 다른 동작을 수행하는 애드온을 만든다

 

1) 프로퍼티 그룹 클래스

import bpy
import random

class MyProperties(bpy.types.PropertyGroup):
    random_number : bpy.props.IntProperty(name="Random Number", default=0)
    text_list = ["First Option", "Second Option", "Third Option"]
    
...

 

MyProperties 프로퍼티 그룹 클래스를 생성한다

생성한 랜덤 정수값을 저장하는 random_number 프로퍼티

정수값에 따라 다른 문자열을 저장text_list 프로퍼티를 추가한다

 

2) 메인 패널 클래스

...

class grn_PT_main_panel(bpy.types.Panel):
    bl_label = "Main Panel"
    bl_idname = "grn_PT_main_panel"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = "New Tab"
 
    def draw(self, context):
        layout = self.layout
        scene = context.scene
        mytool = scene.my_tool
        
        layout.label(text=mytool.text_list[mytool.random_number])
        layout.prop(mytool, "random_number")
        layout.operator("grn.myop_operator")
        
...

 

메인 패널 클래스를 위와 같이 추가한다

패널의 역할을 수행하기 위해 bpy.types.Panel 클래스를 상속받는다

패널을 설정하는 draw 함수에서layout과 관련하여 다음의 설정을 진행한다

  • label : 생성된 랜덤한 정수값에 따라 변경
  • prop : 랜덤한 정수값을 보여주기 위한 역할
  • operator : layout에서 수행할 연산 설정

 

3) Operator 클래스

...

class grn_OT_my_op(bpy.types.Operator):
    bl_label = "Generate Random Number"
    bl_idname = "grn.myop_operator"
        
    def execute(self, context):
        scene = context.scene
        mytool = scene.my_tool
        
        
        x = random.choice(range(0, 3))     
        mytool.random_number = x
        
        
        return {'FINISHED'}
        
...

 

패널에서 수행할 기능을 정의하는 Operator 클래스는 위와 같이 정의하였다

수행할 연산을 설정하는 execute 함수에서는 random 모듈의 choice 함수를 사용하여

0 ~ 2사이의 정수값을 가져와 프로퍼티에 설정하도록 구성하였다

 

4) 클래스의 등록 / 등록해제

...

classes = [MyProperties, grn_PT_main_panel, grn_OT_my_op]
 
 
def register():
    for cls in classes:
        bpy.utils.register_class(cls)
        
    bpy.types.Scene.my_tool = bpy.props.PointerProperty(type=MyProperties)
    

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)
    
    del bpy.types.Scene.my_tool
 
 
if __name__ == "__main__":
    register()

 

생성한 클래스들을 등록 / 등록해제하기 위해 register 함수unregister 함수를 오버라이드한다

 register 함수에서 프로퍼티 그룹 클래스 scene.my_tool 프로퍼티에 등록하도록 로직을 구성하였다

 

- 최종 실행 결과

 

728x90
반응형

'blender > blender python' 카테고리의 다른 글

리스트  (0) 2025.08.19
안개 효과 생성  (0) 2025.08.13
모듈 임포트  (0) 2025.08.06
프로퍼티 서브타입  (0) 2025.08.06
프로퍼티 그룹  (0) 2025.08.06