0
$\begingroup$

I need to have access to the active material and its nodes (if they exist), so I wrote this script that has a problem, when the object has no materials, when the object does not exist, and of course if the object is 'MESH' type

import bpy 

ob = bpy.context.active_object
index = ob.active_material_index     
mat = ob.material_slots[index].material
nodes = mat.node_tree.nodes
my_node = nodes.get("My node name")

if my_node:
    print("My node is inside!")
else:
    print("My node not inside!")

work only if object is not none, object is 'MESH' type and If inside have slot material. else rightly give me that error:

IndexError: bpy_prop_collection[index]: index 0 out of range, size 0

I can't figure out how to assign variables in an if statement, because I know that in python you can't (I think)

$\endgroup$

1 Answer 1

1
$\begingroup$

You can find more info on if statements in Python here.

You can find a lot of useful information about bpy in Blender's Python console using the auto complete function (Ctrl+Space):

enter image description here

The script you are after could be something like this:

import bpy

obj = bpy.context.object
name = "My_node_name"
if obj is not None:
    if obj.type == 'MESH':
        if obj.active_material is not None:
            if obj.active_material.use_nodes:
                nodes = obj.active_material.node_tree.nodes
                if nodes.get(name) is not None:
                    print(name + " node is in the material's node tree.")
                else:
                    print(name + " node is not in the material's node tree.")
            else:
                print("Material does not ue nodes.")
        else:
            print("Object does not have an active material.")    
    else:
        print("Object is not a mesh.")
else:
    print("There is no active object currently in the scene.")
$\endgroup$
1
  • $\begingroup$ Ty for my script it worked well $\endgroup$
    – Noob Cat
    May 20, 2019 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.