Let's not forget about attr_writer, even though you'd normally use attr_accessor instead...
@Star: There's a grave logical error in your post, regarding variable assignment. If you want to set a variable, that variable needs to be
before the equal sign, while the value you set it to comes after. It might be confusing for you because it's two variables with about the same name, but just look at this line and you'll see that it makes no sense:
23 = @foo # totally false
As far as variable types go, let's have a look...
[rgss]variable = 0 # local variable that is accessable within the current method only and gets unset when the method's ran through
@variable = 0 # instance variable that can be used within your whole class and won't be unset
@@variable = 0 # class variable that can be addressed by not only the current class, but all classes within the same superclass
$variable = 0 # global variable that can be addressed anywhere, however is very resource-intensive and should be used only if crucially necessary (which is almost never the case)
[/rgss]
In general, as the types of variables go, you'd choose them in order of necessity. In other words, while you could use a global variable for everything, if you just need to pass values within the method, you'd stick to a local variable instead. If you realize that won't be enough, use an instance variable, and so forth.
As the use of attributes can be a bit confusing, let's see a very simple example class...[rgss]class Game_Example
attr_reader :test_variable
def initialize
@test_variable = 20
end
end
[/rgss]Let's assume you called this class from your imaginary Scene_Map class, for example like this, you could return the value of the variable given above as seen in the update method:[rgss]class Scene_Map
def start
@example = Game_Example.new
end
def update
print @example.test_variable # this would return an undefined variable error without putting the attr_reader in Game_Example
end
end
[/rgss]Now if you also want to change the variable from the class, you'd need to change the attr_reader into attr_accessor, so you could do this:[rgss] def update
@example.test_variable = 40 # this would return an error without attr_accessor
end
[/rgss]Last but not least, note that now that you only modify and not try to read the variable, attr_writer would be sufficient. However, noone really uses it, and it's quite pointless anyway (even though you can't always just use attr_accessor, for example for some more advanced stuff).
You should see that these attributes are quite awesome, as you can keep every classes variables neatly by itself and access them from other classes with ease. This is also how you can access some variables from Game_Character, for example, that are quite useful for scripting - go in there and compare the initialized variables with the ones that are actually attributed.