0
$\begingroup$

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
$\endgroup$
3
  • 1
    $\begingroup$ Hello, you should use the properties defined in 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$
    – Gorgious
    Commented Feb 23, 2023 at 13:38
  • $\begingroup$ Thanks @Gorgious, do you mind giving an example? Should I just put self.objin my_pointer = PointerProperty(name="My Pointer", type=self.object) ? $\endgroup$
    – nammerkage
    Commented Feb 23, 2023 at 14:31
  • 1
    $\begingroup$ You need to use bpy.types.PropertyGroup as a base class and define bpy.props.PointerProperty members inside it $\endgroup$
    – Gorgious
    Commented Feb 23, 2023 at 16:29

1 Answer 1

0
$\begingroup$

Found out why! to get the bpy.obj from the Material class, I need to select: self.obj.data.materials.append(self.material.material)...

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .