Announcements

Starting in December, we will archive content from the community that is 10 years and older. This FAQ provides more information.

Random Select Objects in Group by Percentage in Mel?

victorbennett
Contributor
Contributor

Random Select Objects in Group by Percentage in Mel?

victorbennett
Contributor
Contributor

Can someone help me figure out how to write out a way to randomly select objects that are in a group by a percentage in Mel?  I need to embed this into another script I'm making. 

 

Thanks!

 

Vic

Reply
Accepted solutions (1)
3,555 Views
6 Replies
Replies (6)

mcw0
Advisor
Advisor

string $objects[] = `listRelatives -type "transform" -pa "yourGroup"`;  //  FIRST GET OBJECTS IN GROUP

int $num = size($objects);  //  NUMBER OF OBJECTS

float $percent = 50.0;  //  NOW SET YOUR PERCENTAGE OF OBJECTS TO SELECT

int $numToSelect = ($percent/100.0) * $num;  //  ACTUAL NUMBER OF OBJECTS TO SELECT

//  USE A RANDOM NUMBER FUNCTION TO DETERMINE IF AN OBJECT IS SELECTED OR NOT

float $threshold = $percent/100.0;  //  SINCE THIS EXAMPLE USES 50%, A THRESHOLD OF .5 IS USED

string $list[];  //  RECORD THE OBJECTS TO SELECT

while(size($list) < $numToSelect)  //  KEEP SELECTING UNTIL DESIRED PERCENTAGE IS ACHIEVED

{

    for($object in $objects)  //  LOOP THROUGH YOUR OBJECTS TO DETERMINE WHICH ARE SELECTED

    {

        if(rand(1) > $threshold)

            $list[size($list)] = $object;

    }

    $objects = stringArrayRemove($list, $objects);  //  REMOVE SELECTED OBJECTS FROM YOUR ORIGINAL LIST

}

 

 

This was typed without trying it in Maya.  But the logic is there.  And I'm pretty sure it will work.  Using a "while" conditional is always hazardous, but in this case, you will eventually hit your percentage so it shouldn't go into an endless loop.  Good luck.

victorbennett
Contributor
Contributor

Thanks!  However, it's not selecting anything and I'm not getting any errors...

 

Vic

mcw0
Advisor
Advisor
Accepted solution

I'm so sorry.  I forgot the last line!!!

 

select -r $list;

victorbennett
Contributor
Contributor

Works great.  Thanks!

shmelov
Community Visitor
Community Visitor

This topic made my day. Many thanks to autor, and especialy to mcw0. That script solved a big problem for me!

victorbennett
Contributor
Contributor
So glad it helped!
0 Likes