Skip to content

Instantly share code, notes, and snippets.

@CGArtPython
Last active September 10, 2024 22:02
Show Gist options
  • Save CGArtPython/eca5ee83cfd3315379877e2e294498dd to your computer and use it in GitHub Desktop.
Save CGArtPython/eca5ee83cfd3315379877e2e294498dd to your computer and use it in GitHub Desktop.
Beginner Blender Python Tutorial: Python Classes example 1 (used in tutorial: https://youtu.be/t2KEolkhIoA)
import bpy
class SquareFaceCube:
"""
a class to represent a cube mesh object with square faces
"""
def __init__(self):
# define the coordinates of each vertex
self.verts = [
(-1.0, -1.0, -1.0),
(-1.0, 1.0, -1.0),
(1.0, 1.0, -1.0),
(1.0, -1.0, -1.0),
(-1.0, -1.0, 1.0),
(-1.0, 1.0, 1.0),
(1.0, 1.0, 1.0),
(1.0, -1.0, 1.0),
]
# define faces using the indexes of the vertices
self.faces = [
(0, 1, 2, 3),
(7, 6, 5, 4),
(4, 5, 1, 0),
(7, 4, 0, 3),
(6, 7, 3, 2),
(5, 6, 2, 1),
]
self.mesh_data = None
self.mesh_object = None
def create_mesh_data(self):
"""
create a mesh from the vert and face data
"""
self.mesh_data = bpy.data.meshes.new("cube_data")
self.mesh_data.from_pydata(self.verts, [], self.faces)
def create_mesh_object_from_data(self):
"""
create a object using the mesh data
"""
self.mesh_object = bpy.data.objects.new("cube_object", self.mesh_data)
def add_mesh_object_into_scene(self):
"""
add object into active scene by linking the object into the
default scene collection
"""
bpy.context.collection.objects.link(self.mesh_object)
def create_mesh_object(self):
"""
create a mesh object from the given verts and faces
add the new mesh object into the scene
"""
self.create_mesh_data()
self.create_mesh_object_from_data()
self.add_mesh_object_into_scene()
def add_into_scene(self, location):
if self.mesh_object == None:
self.create_mesh_object()
self.mesh_object.location = location
else:
print("Warning: can't add mesh object because it is already added into the scene")
def main():
square_face_cube = SquareFaceCube()
square_face_cube.add_into_scene(location=(0, 0, 0))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment