Last active
          August 8, 2022 05:18 
        
      - 
      
- 
        Save CGArtPython/05df00d03ef2325639849d4e7cea3874 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 2 of a video tutorial https://www.youtube.com/watch?v=WnZX--idSQI
  
        
  
    
      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 | |
| def get_random_color(): | |
| """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) | |
| return color | |
| def generate_random_color_materials(obj, count): | |
| """create and assign materials to the object""" | |
| for i in range(count): | |
| mat = bpy.data.materials.new(name=f"material_{i}") | |
| mat.diffuse_color = get_random_color() | |
| obj.data.materials.append(mat) | |
| def add_ico_sphere(): | |
| """add an ico sphere""" | |
| bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=3) | |
| return bpy.context.active_object | |
| def assign_materials_to_faces(obj): | |
| """iterates over all the faces of the object and | |
| assigns a random material to the face""" | |
| # turn ON Edit Mode | |
| bpy.ops.object.editmode_toggle() | |
| # deselect all faces | |
| bpy.ops.mesh.select_all() | |
| # get geometry data from mesh object | |
| bmesh_obj = bmesh.from_edit_mesh(obj.data) | |
| # get the number of materials assigned to the object | |
| material_count = len(obj.data.materials) | |
| # iterate through each face of the mesh | |
| for face in bmesh_obj.faces: | |
| # randomly select a material | |
| obj.active_material_index = random.randint(0, material_count) | |
| # 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() | |
| ico_object = add_ico_sphere() | |
| # create a variable for holding the the number of materials to create | |
| material_count = 30 | |
| generate_random_color_materials(ico_object, material_count) | |
| assign_materials_to_faces(ico_object) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment