Based on all the helpful information in the answers to my previous question I have a new question. I will be generating a large number of meshes and animating them using just a script. In the following code, I use bpy.ops.mesh.primitive_uv_sphere_add
to make a sphere, and bpy.data.objects.new
to make a custom mesh. In both cases, it is sometimes necessary to access the object through bpy.context.active_object
and also through bpy.ops.object
. After the whole script runs, the fourth sphere is unintentionally smooth, because it is still active.
My question is partly how to fix this (make only the purple mesh smooth), but I want to check that these are really the most correct and safest and foolproof ways to do this. How do I "know" if bpy.ops.object
really refers to the same object as bpy.context.active_object
? Assume this is in a large script generating and deleting a large number/variety of meshes and objects and materials, vertices are being adjusted, keyframes and shapeframes are doing their thing, etc.
Last question didn't have enough code, so maybe I've overcompensated with too much this time:
import bpy
import numpy as np
nx, ny = 20, 30
x = np.linspace(0, 3, nx)
y = np.linspace(0, 3, ny)
X, Y = np.meshgrid(x, y)
Z = np.cos(X**2 + Y**2)
verts = [tuple(thing) for thing in zip(X.flatten(), Y.flatten(), Z.flatten())]
corner_verts = [verts[0], verts[nx-1], verts[-nx], verts[-1]]
faces = []
for iy in range(ny-1):
for ix in range(nx-1):
v1 = iy*nx + ix
v2 = v1 + 1
v3 = v2 + nx
v4 = v3 - 1
faces.append((v1, v2, v3, v4))
purp = bpy.data.materials.new("PKHG")
cy = bpy.data.materials.new("PKHG")
purp.diffuse_color = (1, 0, 1)
cy.diffuse_color = (0, 1, 1)
puv_add = bpy.ops.mesh.primitive_uv_sphere_add
for vert in corner_verts:
puv_add(segments=8, ring_count=4, size=1, location=vert)
ao = bpy.context.active_object
ao.active_material = cy
me = bpy.data.meshes.new('timmesh')
ob = bpy.data.objects.new('timobj', me)
sco = bpy.context.scene.objects
sco.link(ob)
me.from_pydata(verts, [], faces)
ob.active_material = purp
# the above script leaves the mesh unselected for some reason
ob.select = True
boo = bpy.ops.object
boo.shade_smooth()
ao = bpy.context.active_object
print("ao: ", ao.name) # Sphere.003
print("ob: ", ob.name) # timobj
print("boo: ", boo.name) # <function bpy.ops.object.name at 0x117028470'>
edit (a question from the comments)
since a script does not use a mouse, why does it have to worry about selecting and deselecting and what is or isn't active. I am wondering how I can just give them a reference such as ob and then just do these things without having to constantly manage selection in the script?