How do I delete randomly a specified percentage of geometry objects?

new.gif MAXScript Frequently Asked Questions

A user asked:

I'm trying to create a script that will delete a certain percentage of the objects in a scene. I want the objects to be chosen randomly. I want the script to affect only the meshes.


Here is a possible approach:


-- Collect the object of a certain type into an array, for example

-- this one collects all geometry objects, excluding the target objects

-- which are of Geometry superClass for pre-MAXScript historical reasons


candidatesArray = for o in Geometry where classof o != TargetObject collect o


-- Because you want to remove random objects, but a specified percentage,

-- it is a good idea to make the decision which objects will be deleted

-- BEFORE actually deleting any objects.

-- You can create a second array and fill it up with the actual

-- objects to be deleted:


deadRowArray = #() -- init. an empty array

thePercentage = 50.0 -- define the percentage


-- Calculate the number of objects to delete:

numberToDelete = (thePercentage / 100.0 * candidatesArray.count) as integer


-- Loop until the deadRow array gets filled

-- with the desired number of objects:

while deadRowArray.count < numberToDelete do


newIndex = random 1 candidatesArray.countgenerate new random index

--if not already chosen, add it to the deadrow array

if findItem deadRowArray candidatesArray[newIndex] == 0 do

append deadRowArray candidatesArray[newIndex]


delete deadRowArray --finally, delete the selected objects

See also

Frequently Asked Questions