Skip to content

How to create a class in MaxScript

November 16, 2012

For anyone who is masochistic enough to have used MaxScript you probably know that it doesn’t have classes.  The following code snippits are the closest I have come to being able to create classes in external files.  For some reason I’ve never been able to find examples like this when searching google so I figured I would put it here so that my future self will be able to find it in a pinch and hopefully other Technical Artists  out there will find it useful as well.

Place the following code in a file called MyClass.ms:

struct MyClass
(
    public

    -- The constructor function that gets everything started.
    fn Constructor =
    (
        print ("The Constructor has been run")
        return true
    ),

    -- An example public function
    fn MyFunction =
    (
    ),

    initalized = Constructor(), -- This will be executed when this strut is created the first time.

    private

    -- An example private function
    fn MyPrivateFunction =
    (
    )

)

Calling it is also a little tricky to get correct. Put this code in a second file, save it to the same folder as MyClass.ms, and run it:

(
    clearListener()
    Global MyClass;     -- Inform MaxScript that this variable will eventually exist.
    fileIn "MyClass.ms" -- Read in the external class file
    data = MyClass()    -- Create a local instance of the class.

    print ("The class: " + data as string) -- Display the contents of the local instance of the class.
    ""
)

If you did everything correctly, when you run the second script you should see:

"The Constructor has been run"
"The class: (MyClass initalized:true)"
""

Happy Programming!

Advertisements
One Comment
  1. Alejandro Martinez-Chacin permalink

    It has never occurred to me to use a _anyVariableHere = constructor() to trigger a constructor.
    That there, is gold for me, thanks a lot mr.


    Have been going around with this and finally settling with a ‘myStruct.Initialize selfRef’ function.
    Used like this:
    inst = myStruct()
    inst.Initliaze inst -> this Initialize works as the constructor initializer too.

    How are you solving the issue of having ‘this’ or ‘self’ in your class?

    Many thanks already.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: