Monday, April 30, 2012

MEL: How to apply commands to all the objects selected.

Here's how to apply a command or commands to each and every objects that are being selected.

string $selected[] = `ls -sl`;
     for ($member in $selected)
     {
          commands...
     }

The first line is to list all the selected objects, and put the list into a string array variable called $selected. The second line is a for-loop which will execute the commands for all the selected objects.

Notice that $member variable is for-loop internal variable which doesn't need to be declared.
It is only used inside of the for-loop.

For example, you can rename all the selected objects at one shot.

string $selected[] = `ls -sl`;
     for ($member in $selected)
     {
          rename $member "myObject#";
     }

If you execute this script, your selected objects will become myObject1, myObject2, myObejct3....


Here's another example.
You can add a new attribute to all the objects you select.
Let's add miLabel attribute.

string $selected[] = `ls -sl`;
     for ($member in $selected)
     {
          addAttr -ln miLabel -at long -min 0 -max 10 -dv 1 $member;
          setAttr -e keyable true ($member +".miLabel");
     }

This script is to add "miLabel" attribute to all the selected objects, and set its initial value to 1.

This is one of the most frequently used mel scripts. It can be used in many different ways.

1 comment: