01: meet the for loop, my best friend
string $sel[] = `ls -sl`; for ( $i=0; $i<size($sel); $i++ ){ setAttr ($sel[$i] + ".someAttribute") $someValue }
The most useful thing about MEL, in my opinion, is that it makes working in Maya soo much quicker. Especially mass editing and automating repetitive tasks.
How many times have you gone through objects, one by one to change an attribute that doesn't show up in the channel box (where mass editing is possible)?
Next time, check the script Editor and notice the output from changing an attribute, say, the 'visible' attribute of an object (effectively hiding it). The output says:
setAttr "someNode.visibility" 0;
Now, in the Script Editor, write:
string $sel[] = `ls -sl`; for ( $i=0; $i<size($sel); $i++ ){ setAttr ($sel[$i] + ".visibility") 0; }
and select multiple objects in the view port. Now, select what you wrote in the Script Editor and press the 'enter' button on the numeric pad, which will execute the script.
The script will 'ls -sl' (list the selected objects) and store them in a data collection called $sel (note the brackets, defining $sel as an array). The backward ticks tells maya to store the RESULT of the 'ls' command, rather than the words "ls -sl". The backward tick is produces by pressing the button left of '1'. Again, you want ` not '.
Then it will say "for each item in the list, do:...". Actually, it say "for (start at 0, the first item, and as long as the item number is less than the number of items in the list, do whatever I'll say and after each time I've done it, I'll increase the item index and do it again)".
The curly brackets define a "scope". Every thing within the scope will be executed for each time the loop runs.
There are other ways of writing loops as well. Look it up in the documentation, or on the web.
Examples are: while loop, if loop, case/switch loop and "for ($element in $list)" loop (only works on strings)
So, here is a good example:
Say you have a lot of objects that you use in you render layer for casting reflections (shaded or textured with a projection of the shot plate. You either need to go through them one by one and setting primary visibility to '0' (or if they are textured with the projected shot plate also set 'casts shadow' and receive shadow' to '0'), or select all in on go and run:
string $sel[] = `ls -sl`; for ($i=0; $i<size($sel); $i++){ string $shape[] = `listRelatives -s $sel[$i]`; setAttr ($shape[0] + ".castsShadows") 0; setAttr ($shape[0] + ".receiveShadows") 0; setAttr ($shape[0] + ".motionBlur") 0; setAttr ($shape[0] + ".primaryVisibility") 0; }











