First blender script need helps regarding if statement

Hi, I managed to make my first working script and I’m very proof of it! To improve it a bit I would like to know how I could add an if statement or something like that:
If the image node with the color grid loaded into already exist plug it to the Principled BSDF if not then execute my script:
Here my working script that create a color grid texture and plug it into the BSDF color slot

import bpy

material_current = bpy.context.object.active_material
principled_node = material_current.node_tree.nodes.get('Principled BSDF')
texture_node = material_current.node_tree.nodes.new('ShaderNodeTexImage')
texture_node.location = (-300, 300)
texture = bpy.ops.image.new(name='Color Grid', width=1024, height=1024, alpha=False, generated_type='COLOR_GRID')
imagename = bpy.data.images.get("Color Grid")
if imagename:
    texture_node.image = imagename
link = material_current.node_tree.links.new
link(texture_node.outputs[0], principled_node.inputs[0])

First, congrats on your first script and welcome to coding! It’s a journey, sometimes fun, sometimes irritating, but usually worth the eventual time savings you get!

Second, what you want is called try/except/else. I highly recommend a book called “Automate the Boring Stuff with Python” (https://automatetheboringstuff.com/) for getting your feet wet.

I don’t want to just give you a precise example to copy/paste because that might deprive you of the lesson, but basic idea is that try will do something and you can tell it what to do if it succeeds or what to do if it gives you an error.

1 Like