I'm trying to make a material class in Python. I want to assign it to a custom text class.
I have a code, which makes a text object, and if no material is assigned it just makes a black material.
But, I would love to make the same black material and assign it by passing it into the Text class. However, this does not work.
I know my code looks silly with the dataclass
and KW_ONLY
, but this is my stripped down version of the code:
import bpy
from dataclasses import dataclass, KW_ONLY
@dataclass
class Material:
def __post_init__(self):
self.material = bpy.data.materials.new(name="Black")
self.material.diffuse_color = (0,0,0,1)
@dataclass
class Text():
_: KW_ONLY
material: None = field(default=None)
def __post_init__(self):
font_curve = bpy.data.curves.new(
type="FONT",
name="Font Curve")
self.obj = bpy.data.objects.new(
name="Font Object",
object_data=font_curve
)
# add to scene
bpy.context.scene.collection.objects.link(self.obj)
# material
if self.material == None:
mat = bpy.data.materials.new(name="Black")
mat.diffuse_color = (0,0,0,1)
self.obj.data.materials.append(mat)
else:
# PASSING MATERIAL OBJECT, DOES NOT WORK
self.obj.data.materials.append(self.material)
Text() #works
# Let's pass a material
mat1 = Material() #works
Text(material = mat1) #fails
bpy.props
to hold pointers to object. The python API is just a bridge to the actual data, and the pointer adresses may change without a warning, when you save / load, undo / redo, etc. Some objects will give a different pointer adresss everytime you try to fetch them. So I think your solution is bound to experience a lot of bugs due to serialization problems $\endgroup$self.obj
inmy_pointer = PointerProperty(name="My Pointer", type=self.object)
? $\endgroup$bpy.types.PropertyGroup
as a base class and definebpy.props.PointerProperty
members inside it $\endgroup$