I have a .blend and a addon.py file. I try to import the node group by finding the node group file in the .blend and then import it, but just creates a missing data link node. I have also tried hardcoding the path, but still not working. Using blender 4.0. Thanks for any help!
def create_material(context):
# Create a new material
mat = bpy.data.materials.new(name="PlanetMaterial")
# Enable nodes for the material
mat.use_nodes = True
# Get the material nodes
nodes = mat.node_tree.nodes
# Clear existing nodes
for node in nodes:
nodes.remove(node)
# Get the directory where user scripts (including add-ons) are located
script_path = bpy.utils.script_path_user()
# Construct the path to the blend file containing the node group
node_group_file = os.path.join(script_path, "addons", "planet_node_group.blend")
# Load the node group from the blend file
with bpy.data.libraries.load(node_group_file, link=False) as (data_from, data_to):
node_group_name = "Planet Material" # Adjust this to match the actual name of your node group within the blend file
if node_group_name in data_from.node_groups:
data_to.node_groups = [node_group_name]
# Get the newly loaded node group
node_group = data_to.node_groups[0]
else:
print(f"Node group '{node_group_name}' not found in the blend file.")
return
# Add the node group to the material's node tree
group_node = nodes.new(type='ShaderNodeGroup')
group_node.node_tree = node_group
# Get the selected object or the newly created UV sphere (planet)
obj = context.active_object
# Assign the material to the object (if it's a mesh object)
if obj and obj.type == 'MESH':
if obj.data.materials:
# If the object already has materials, replace the first one
obj.data.materials[0] = mat
else:
# If the object doesn't have any materials, append the new one
obj.data.materials.append(mat)
else:
print("Selected object is not a mesh object, cannot assign material.")