0

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?

boomstick
  • 53
  • 1
  • 9

1 Answers1

2

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))
Green Cell
  • 4,677
  • 2
  • 18
  • 49
  • Hey @Green-cell! Not sure if you’re going to see this comment but I was wondering how would I go about creating a list of those meshes to track how many are in a scene? It can’t be as simple as primitives = cmds.ls(‘myMesh’)? This way I could control how many of them are in the scene and could delete them if necessary. Thanks. – boomstick Apr 08 '19 at 14:37
  • You can list objects and filter by type, so if you mean all meshes you can do `cmds.ls(type="mesh")`, or if you want specific types you can do `cmds.ls(type="polySphere")` – Green Cell Apr 08 '19 at 16:04