Reputation: 63
I am trying to spawn a random polygon primitive with a random number of subdivisions each time.
If my limited knowledge is correct I can't just spawn a random mesh. I would need to collect all types of meshes I could spawn into an array of numbers and then pull a random number which represents that mesh and spawn it.
However each mesh has a different command/way of subdividing itself.
import random
object = cmds.polySphere ( r=10, sx=random.randrange(10, 100), sy=random.randrange(10,100), name='mySphere#' )
I can spawn each mesh separately and randomize it based on specific commands but how would I get it to spawn either a cube, a cone or any other primitive with a random number of divisions?
Upvotes: 0
Views: 373
Reputation: 4777
The interesting thing with creating primitives is that their return values are consistent. They always return a transform and a shape, for example:
cmds.polyCube()
# Result: [u'pCube1', u'polyCube1'] #
cmds.polyCone()
# Result: [u'pCone1', u'polyCone1'] #
cmds.polySphere()
# Result: [u'pSphere1', u'polySphere1'] #
And luckily every division attribute has the word "subdivision"
in it, so we can set a random value to any attribute that has that word in it.
Knowing this we can pick a random primitive to create, then loop through its shape's attributes to set a random subdivision:
import random
import maya.cmds as cmds
# Define a list of all primitive functions we can create from.
primitives = [cmds.polySphere, cmds.polyCube, cmds.polyCylinder, cmds.polyCone, cmds.polyTorus, cmds.polyPlane]
# Pick a random primitive and create it.
mesh_type = random.choice(primitives)
transform, shape = mesh_type()
# Set a random value on any attribute that has subdivision in its name.
attrs = cmds.listAttr(shape, keyable=True)
for attr in attrs:
if "subdivision" in attr:
cmds.setAttr(shape + "." + attr, random.randrange(10, 100))
Upvotes: 2