Hi all,
I spend most of my time on this forum trying to understand a little bit more what Maxscript can make for me and i really enjoy it.
I’m currently working on a script which bakes the whole materials into a single diffuse map. The baking function can be called with a button or within another function. It works flawlessly when i press on the button, but when it’s launched within the global func the unwrapping result is totaly strange.
It looks like the object was shot from above like a planar projection but with some holes (screenshots included).
Here’s the code of my baking function :
fn BakeDiffuse obj size opaque keepmat =
(
local UVWMod
local unwrapMod
local bakeChannel_Obj = 3
local flattenAngle = 45
local flattenSpacing = 0.002
local flattenRotate = true
local flattenFillHoles = true
for m in obj.modifiers where m.name == "Unreal Lightmass" do deleteModifier obj m
unwrapMod = unwrap_UVW()
unwrapMod.setAlwaysEdit false
unwrapMod.setMapChannel bakeChannel_Obj
unwrapMod.setFlattenAngle flattenAngle
unwrapMod.setFlattenSpacing flattenSpacing
unwrapMod.setFlattenNormalize true
unwrapMod.setFlattenRotate flattenRotate
unwrapMod.setFlattenFillHoles flattenFillHoles
unwrapMod.setApplyToWholeObject true
unwrapMod.name = "Unreal Lightmass"
unwrapMod.setDebugLevel 0
addModifier obj unwrapMod
unwrapMod.flattenMap flattenAngle #() flattenSpacing true bakeChannel_Obj flattenRotate flattenFillHoles
escapeEnable = true
unwrapMod.packNoParams()
rendTimeType = 4
rendPickupFrames = "0"
vr=renderers.current
vr.output_splitRGB = true
vr.output_splitAlpha = true
RGBFile = maxfilepath+filenameFromPath (getDir #image+"\\"+obj.name+".RGB_color.0000.jpg")
AlphaFile = maxfilepath+filenameFromPath (getDir #image+"\\"+obj.name+".Alpha.0000.jpg")
vr.output_splitfilename = maxfilepath+filenameFromPath (getDir #image+"\\"+obj.name+".jpg")
obj.iNodeBakeProperties.removeAllBakeElements()
be1 = VRayCompleteMap() --instance of the bake element class
be1.outputSzX = be1.outputSzY = size
be1.filterOn = true
be1.enabled = true
obj.INodeBakeProperties.addBakeElement be1
obj.INodeBakeProperties.bakeEnabled = true
obj.INodeBakeProperties.bakeChannel = 3
obj.INodeBakeProperties.nDilations = 2
select obj
render rendertype:#bakeSelected vfb:off progressBar:true outputSize:[size,size]
theComp = bitmaptexture filename:RGBFile
theComp.coords.mapChannel = 3
theAlpha = bitmaptexture filename:AlphaFile
theAlpha.coords.mapChannel = 3
if opaque == true then
(
bakedMat = standard diffusemap:theComp opacitymap:theAlpha selfIllumAmount:100 opacity:100
)
else
(
bakedMat = standard diffusemap:theComp selfIllumAmount:100 opacity:15
)
if KeepMat == True then
(
obj.material = Shell_Material originalMaterial:obj.material bakedMaterial:bakedMat renderMtlIndex:0 viewportMtlIndex:1
showTextureMap obj.material obj.material.bakedMaterial true
)
else
(
obj.material = bakedMat
showTextureMap obj.material on
)
)
Any help would be more than welcome ! 
Screenshots :
