Last active
November 27, 2023 10:45
-
-
Save CGArtPython/25c37feb8484776306b5a5a98648d4ca to your computer and use it in GitHub Desktop.
A Blender Python script to generate an ico sphere with random colors applied to each face. Part 1 of a video tutorial https://www.youtube.com/watch?v=VpPwAsI12CQ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# give Python access to Blender's functionality | |
import bpy | |
# give Python access to Blender's mesh editing functionality | |
import bmesh | |
# extend Python functionality to generate random numbers | |
import random | |
# add an ico sphere | |
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=3) | |
ico_object = bpy.context.active_object | |
# turn ON Edit Mode | |
bpy.ops.object.editmode_toggle() | |
# deselect all faces | |
bpy.ops.mesh.select_all() | |
# get geometry data from mesh object | |
ico_bmesh = bmesh.from_edit_mesh(ico_object.data) | |
# iterate through each face of the mesh | |
for face in ico_bmesh.faces: | |
# generate a random color | |
red = random.random() # creates a value from 0.0 to 1.0 | |
green = random.random() | |
blue = random.random() | |
alpha = 1.0 | |
color = (red, green, blue, alpha) | |
# create a new material | |
mat = bpy.data.materials.new(name=f"face_{face.index}") | |
mat.diffuse_color = color | |
# add the material to the object | |
ico_object.data.materials.append(mat) | |
# set active material | |
ico_object.active_material_index = face.index | |
# select the face and assign the active material | |
face.select = True | |
bpy.ops.object.material_slot_assign() | |
face.select = False | |
# turn OFF Edit Mode | |
bpy.ops.object.editmode_toggle() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment