3DS Max/ MaxScript: Attach mesh but keep Material IDs

When you're trying to perform meshop.attach in MaxScript you get MaterialIDs fucked up (not in all cases, but mostly). So I faced the problem when I needed to attach meshes, but keep their material IDs for further usage.

Looking over Internet gave almost nothing and I decided to first read material IDs to array and then write them back and it worked for me.

I publish here my function and an example of usage.
It works with Editable Meshes only, but it's not that hard to make it work with polyop (I just didn't have such problem yet).

Here is the code:

Function itself
12345678910111213141516171819202122232425
fn attachMeshKeepMatIds obj1 obj2 = 
(
	matIds = #()
	
	faceIndex = 0
	
	for i=1 to getNumFaces obj1 do
	(
		faceIndex = faceIndex + 1
		matIds[faceIndex] = getFaceMatID obj1 i
	)
	
	for i=1 to getNumFaces obj2 do
	(
		faceIndex = faceIndex + 1
		matIds[faceIndex] = getFaceMatID obj2 i
	)
		
	meshop.attach obj1 obj2
		
	for i=1 to getNumFaces obj1 do
	(
		 setFaceMatID obj1 i matIds[i]
	)	
)

Usage example:
123456789101112
firstObj = undefined
for obj in (selection as array) do
(
	if firstObj == undefined then
	(
		firstObj = obj		
	)
	else
	(
		attachMeshKeepMatIds firstObj obj
	)
)

You can leave a comment with "Facebook":
Не забывайте оставлять комментарии при помощи "ВКонтакте":
Яндекс.Метрика