Using Structs as Classes In Maxscript

So on Friday I learned, after promising my team a whole new set of maxtools, that maxscript doesn’t have classes, and therefore no way of properly handling modules or scripts split into multiple files. Madness! (I mean, my fault for presuming I’d be able to jump into maxscript that easily, but I figured it couldn’t be that different from Maya Python…)

Anyway, this meant that my toolkit only worked once, in the session that the macro had first been ran. When max was opened for a second time, everything global that was brought in using fileIn was not being treated as such.

To fix this, I used Neil Marshall’s tutorial on how to have a struct act like a class in maxscript, eliminating the need for everything to be global! The variables I needed were declared when I called the constructor of the class, as part of the macroscript, then lived in that scope after that.

So the struct looks like this:

struct variablesClass
(
public

function Constructor =
(
print “Constructing Class”
global me = “Amy”
global you = “Max”
global feelings = “Confusion”
return true
),

function testPrint =
(
print “—————-”
print me
print you
print feelings
print “—————-”
),

initalized = Constructor()

)

and then my script looks like this:

macroScript Test1
category: “Tests”
tooltip: “Test 1”
(
global variablesClass
fileIn “C:/Users/Amy/Desktop/variables.ms”
myVars = variablesClass()

print (“The class: ” + myVars as string)

myVars.testPrint()
)

You can see below that when the macro is run, the constructor is run.  We are able to see the instance of the “class” by printing it and then we can run functions from the struct that use the variables declared in the constructor.

Capture.PNG

To be able to access individual variables, rather than make them global, I declared them in the struct and then called them from there.

Capture2

So it looks like I’ve got a solution for splitting files into modules in maxscript! Going to be a fun day of refactoring tomorrow…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s