忘却まとめ

Blenderの中級者・上級者向けの踏み込んだ情報や、アドオン・3DCGに関する情報を記事にします

Propertyのdefault値をユーザー設定にする方法【Blender/Python】

Python

投稿日:

ユーザーがプロパティのdefault値を変更できると、ユーザーがよく使う値を初期値に始められるので色々と便利である。
これの作り方の注意点を紹介する。

失敗例

props_main.pyは、シーンのPropertyを作るファイル。StringPropertyのdefault値にユーザー設定のものを設定すれば、簡単に実装できるように思える。
しかし、実際は、アドオンを読み込んだ際に「~.preferencesがNonetype」とのエラーが出てしまう。

# props_main.py

import bpy
from bpy.props import *
from bpy.types import PropertyGroup

class HOGE_PR_main(PropertyGroup):
	def_path = bpy.context.preferences.addons[__name__.partition('.')[0]].preferences.default_user_path
	user_path : StringProperty(name="User Path",default=def_path)
# __init__.py

from .props_main import HOGE_PR_main 

classes = (
HOGE_AddonPreferences,
HOGE_PR_main,
)


def register():
	for cls in classes:
		bpy.utils.register_class(cls)

	bpy.types.Scene.hoge_props= PointerProperty(type=HOGE_PR_main)


def unregister():
	for cls in reversed(classes):
		bpy.utils.unregister_class(cls)

	del bpy.types.Scene.hoge_props

修正後

__init__.pyでの読み込み順番に問題があるため、エラーが起こる。
Pythonでは、ファイルを読み込んだ時点で中身も読まれている。そのため、まだアドオン設定を登録されていないタイミングでPropertyGroupを読んでしまい、存在しないアドオン設定を見ていることになってしまっていることが原因。

アドオン設定のクラスを登録した後に、register()内でファイルをインポートし、登録するように読み込み方を修正する。

# インデントがない箇所にfrom .props_main を書いてはいけない

classes = (
HOGE_AddonPreferences,
)


def register():
	for cls in classes:
		bpy.utils.register_class(cls)

	# アドオン設定が読み込まれた後に、register()内で読み込む
	from .props_main import HOGE_PR_main 
	bpy.utils.register_class(HOGE_PR_main)
	bpy.types.Scene.hoge_props = PointerProperty(type=HOGE_PR_main)


def unregister():
	for cls in reversed(classes):
		bpy.utils.unregister_class(cls)

	from .props_main import HOGE_PR_main
	bpy.utils.unregister_class(HOGE_PR_main)
	del bpy.types.Scene.hoge_props

アドオンの制作依頼はこちら

-Python

Copyright© 忘却まとめ , 2024 All Rights Reserved Powered by STINGER.