Tutorial: Binding script data to switches and variables
RPG Maker comes with switches and variables that are primarily used for data control and logic flow. Furthermore, it would be convenient to users if script options can be assigned to these switches or variables as well.
Script options may be anything in your own scripts that you use to determine your own logic flow for the script, such as a boolean flag that prevent certain parts of the code from running.
Some scripts require script calls in order to enable or disable certain options, or change certain values in specific variables. My preferred way of doing things is to use getter and setter methods and have them reference game switches or variables.
For example, suppose you have some script that shows or hides a minimap. You might store this option in Game_System like
class Game_System attr_accessor :show_minimap end
And then you would instruct users to turn on or off the minimap using the following script calls
$game_system.show_minimap = true $game_system.show_minimap = false
Which works. There is nothing wrong with it, but this means that as a user I don’t get to take advantage of switches or variables that the event editor can handle for me.
How about something like
class Game_System def show_minimap $game_switches[Show_Minimap_Switch] end def show_minimap=(val) $game_switches[Show_Minimap_Switch] = val end end
The change is not particularly significant: you’re simply defining where you get the data and how you set the data. Plus, if the user’s already using script calls before, it isn’t any different now, which is a good thing as it provides backwards compatibility if you are actually making changes to an existing script that people are already using.
The difference occurs in how you are writing the rest of your code. In a minimap script, you might have something in Scene_Map that checks whether the map should be displayed or not
class Scene_Map < Scene_Base alias :th_minimap_update :update def update th_minimap_update update_minimap end def update_minimap hide_minimap unless $game_system.show_minimap # ... end end
Your design provides an intuitive interface to the user (just set some switches or variables), while at the same time allowing you to modularize your code.