Tutorials: Using Scripts to Initialize Objects


What if you have lots of similar objects and want them to share the same description? In most cases, you should use classes and member variables, but this tutorial explores an alternative method which may still be useful in some instances.

See Also...

To perform the same actions of several different events, you can define one script that gets called whenever an event is triggered.


script LookatTree
{
   switch random(3) {
   case 0: "I think I shall never see..."
           "...a thing as branchy as that tree."
   case 1: "Oooh, a tree."
   case 2: "Of all the trees I've ever seen, that is one of them."
   }
}

event Lookat -> Tree1 { LookatTree; }
event Lookat -> Tree2 { LookatTree; }
event Lookat -> Tree3 { LookatTree; }

Whenever the player looks at any of these trees, they will have the same description. Of course, it is usually more fun to make each one different, but suppose there are 20 trees in various scenes in your game, and only five of them have knot-holes with various treasures inside. If you use a script as above, and you want to change the description of all those generic trees, you only have to change it in one place instead of 15!

You can also use a script to construct any number of different objects so that they share some common properties.


script constructPerson (x, y, color)
{
     setPosition(x, y)
     setStopAnim4(JoeStUp_sprite, JoeStRt_sprite,
                JoeStDn_sprite, JoeStLt_sprite);
     setTalkAnim4(JoeTkUp_sprite, JoeStTk_sprite,
                JoeTkDn_sprite, JoeStTk_sprite);
     setClickArea(-20, -80, 20, 0);
     textY = -100;
     textColor(color);
}

object Guy1 { constructPerson(100, 300, ORANGE); }
object Guy2 { constructPerson(700, 350, CYAN); }
object Guy3 { constructPerson(830, 400, PURPLE); }

Now there are three different people with the same animation, but with different positions and text colors. And if you want to change something for all three people, you only have to modify a single script. And of course, you can further specialize each object by adding more statements to the object definition code.

See Also...