Notifications
Clear all

[Closed] Strange error when instancing

Here I am again

I got a code snippet that I hope some of you would care to look at. I am writing a script that replaces a bunch of objects with an instance of a new object. Should be simple (at least in my head), but I find that some objects are not replaced with the code I am using. Here’s a version of the script to try out:

-- Demo objects
 for x = 1 to 20 do
 (
 	for y = 1 to 20 do
 	(
 		box name:(uniqueName"TestBox_") pos:[x, y, 0] width:.5 height:.5 length:.5
 	)
 )
 
 max create mode 
 
 -- Now, replace these boxes with an instanced sphere
 newSphere = sphere pos:[-1, 1, 0] radius:0.25
 
 swapObj = $'TestBox_*'
 numObj = swapObj.count
 
 print ("Replacing " + numObj as string + " objects..." )
 
 for i = 1 to numObj do 
 (
     newO = instance newSphere
     newO.transform = swapObj[i].transform
     newO.name = swapObj[i].name
     delete swapObj[i]
 )

When I run this, only every second row of objects get replaced! Does anyone see what I am doing wrong?

Thanks!

3 Replies
 JHN

Why don’t you just swap baseObjects?


b = box()
s = sphere()
b.baseObject = s.baseObject

No need to worry about transforms anymore. I use this all the time!

-Johan

 JHN

And what you are doing wrong is that you’re deleting objects from 1 to end of the array, so the array is shrinking while you’re still accessing it…
if you delete array[1] then what was array[2] will become array[1]. So it’s not odd you see what you see.
Better would be to loop from the back of the array to zero

for count = array.length to 1 by -1 do etc

Or you could delete the old objects after the complete for loop is done, deleting them all at once.

-Johan

Well, hi again Johan

I couldn’t use baseObject in this script due to stack issues. I found a workaround using instanceReplace() before I posted the original post, but I couldn’t let this version pass without knowing what I was doing wrong.

Now that you mention that I delete the array as I go through it, I finally understand the problem. One part of my brain still thinks the array is just a reference, but it obviously works if I delete the original objects at the end. Thanks again!