MEL How-To #23

Back · Previous · Next Maya

How do I retrieve a list of only the selected Lights (or any other node type that uses a transform/shape pair)?

Well, logically you would think this would do it:

string $selectedLights[] = `ls -sl -lights`;

But -- while this does indeed return the list of selected lights, unfortunately it is only reliable if the user selects the shape node of the light. Often they won't, nor should they be required to.

Fortunately, the "ls" command offers a convenient method for retrieving the shape nodes from the current selection:

string $selectedShapes[] = `ls -selection -dag -leaf`;

By using this query, you need not concern yourself if the user has selected the transform or the shape for a particular node.

From here, you can typically use the "nodeType" command to query if the shape is the type you're looking for:

if ( "mesh" == `nodeType $shape` )
  // Do something with a mesh shape.

if ( "camera" == `nodeType $shape` )
  // Do something with a camera.

However, "light" is not a node type; rather, there are several types of lights: spotLight, directionalLight, etc. A more generalized query is convenient in this case - that provided by the "getClassification" command. This command returns a classification string for the node's type. Be aware that this returns a string array and not just a string.

getClassification spotLight;
// Result: light //

getClassification volumeLight;
// Result: light //

The following procedure demonstrates its use for extracting all lights from the current selection.

proc string[] getSelectedLights()
  string $selectedLights[];

  string $select[] = `ls -sl -dag -leaf`;

  for ( $shape in $select )
    // Determine if this is a light.
    string $class[] = getClassification( `nodeType $shape` );

    if ( ( `size $class` ) > 0 && ( "light" == $class[0] ) )
      $selectedLights[ `size $selectedLights` ] = $shape;

  // Result is an array of all lights included in 
  // current selection list.
  return $selectedLights;

Related How-To's

26 Sep 2004