Skip to content

Instantly share code, notes, and snippets.

@CGArtPython
Created February 20, 2023 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CGArtPython/e6ba86accb113d0d0a7b2b6e776625bc to your computer and use it in GitHub Desktop.
Save CGArtPython/e6ba86accb113d0d0a7b2b6e776625bc to your computer and use it in GitHub Desktop.
Beginner Blender Python tutorial code for creating a simple material and tweak its base color, metallic, and roughness (tutorial https://youtu.be/TdBYf8orLA4)
# give Python access to Blender's functionality
import bpy
# extend Python functionality to generate random numbers
import random
def partially_clean_the_scene():
# select all object in the scene
bpy.ops.object.select_all(action="SELECT")
# delete all selected objects in the scene
bpy.ops.object.delete()
# make sure we remove data that was connected to the objects we just deleted
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
def create_material(name):
# create new material
material = bpy.data.materials.new(name=name)
# enable creating a material via nodes
material.use_nodes = True
# get a reference to the Principled BSDF shader node
principled_bsdf_node = material.node_tree.nodes["Principled BSDF"]
# set the base color of the material
principled_bsdf_node.inputs["Base Color"].default_value = (0.8, 0.120827, 0.0074976, 1)
# set the metallic value of the material
principled_bsdf_node.inputs["Metallic"].default_value = 1.0
# set the roughness value of the material
principled_bsdf_node.inputs["Roughness"].default_value = random.uniform(0.1, 1.0)
return material
def add_mesh():
# create an ico sphere
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=5)
# shade smooth
bpy.ops.object.shade_smooth()
# get reference to mesh object
mesh_obj = bpy.context.active_object
return mesh_obj
def main():
partially_clean_the_scene()
name = "my_generated_material"
material = create_material(name)
mesh_obj = add_mesh()
# apply the material to the mesh object
mesh_obj.data.materials.append(material)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment