Custom methods and objects

 

Custom methods

You already know the engine provides predefined objects (such as actors, entities, scenes etc.) and those objects offer you methods you can call from your scripts. But WME also allows you to define your own methods for these objects. Defining a method is very similar to defining a function, but instead of the function keyword you have to use method keyword. Such a function is then visible from the "outside", i.e. you can call it exactly the same way as the hard-coded engine methods.

All you need to do is:

  1. create a script file
  2. define one or more methods in the script
  3. attach the script to an object (e.g. to an actor)

Example:

method MyTestMethod(parameter)
{
  Game.Msg("This is my test method. The parameter was " + parameter);
}
 

Once you attach the above script to some object (either in the object definition, or using a GUI tool such as SceneEdit, or using the AttachScript method), you can call the method from another script:

SomeObject.MyTestMethod("some parameter");

If you need to reference the object owning the method, use the this keyword. This pseudo-variable holds a reference to the object the current script is attached to.

Due to the nature of the scripting in WME, the engine is unable to detect misspelled method names at compile time; those will be detected at runtime and will cause a runtime error. This is the only drawback of the methods compared to ordinary functions.

You can also override the engine built-in methods, such as Talk or GoTo by simply defining a method with the same name. But it's strongly recommended to call the original method from within your custom implementation. The following example overrides the built-in GoTo method. It writes the requested destination to screen and then calls the original GoTo method to perform the actual walking.

method GoTo(X, Y)
{
  Game.Msg("The actor is about to walk to " + X + ", " + Y);
  this.GoTo(X, Y);
}

 

Custom objects

The previous chapter mentions you can use custom methods to enhance existing engine-defined objects. But WME also allows you to create new object from scratch. First you need to create a script file, containing all the methods your new object should provide. When you want to instantiate the object, use the following syntax:

// create a new object   
        var MyObject = new Object("script_filename");

        // now we can call its methods   
        MyObject.MyMethod();

From now on you can call MyObject's methods as they are defined in the script file, referenced by "script_filename".

You can use this approach for variety of tasks. For example you can create "code libraries", i.e. objects providing various shared utility functions. This is the (only) way how WME supports global functions shared between multiple scripts.