NamedResources tutorial

From Rubygame

Jump to: navigation, search

This wiki has moved! You can view and edit the new wiki on GitHub!

Autoloading Resources

# Import the Rubygame module into the current namespace, so that you can
# type "Surface" instead of "Rubygame::Surface", etc.
include Rubygame
 
# Get the absolute path to the directory that this script is in.
this_dir = File.dirname( File.expand_path(__FILE__) )
 
# Set up autoload directories for Surface, Sound, and Music.
# Surfaces (images) will be loaded from the "images" directory,
# Sounds from "sfx", and Music from "music".
Surface.autoload_dirs << File.join(this_dir, "images")
Sound.autoload_dirs   << File.join(this_dir, "sfx")
Music.autoload_dirs   << File.join(this_dir, "music")
 
# Finds and loads "images/player.png"
player_img = Surface["player.png"]           
 
# Finds and loads "sfx/beep.wav"
beep_sound = Sound["beep.wav"]
 
# Finds and loads "music/theme_song.mp3"
theme_song = Music["theme_song.mp3"]

A Warning About Caching

When a resource is loaded via [] (e.g. Surface["player.png"]), that resource is cached. That means the next time you do Surface["player.png"], it will return the same exact object as it did the first time. This is usually good, because it means that the file does not have to be loaded again every time it is used.

That also means that if you modify that object, the change will affect the object everywhere it is used, which can cause bugs if you aren't expecting it. For example:

player1 = Surface["player.png"]         # => #<Rubygame::Surface:0xfdbb9216a>
player2 = Surface["player.png"]         # => #<Rubygame::Surface:0xfdbb9216a>
 
# Note that player2 now refers to the same object as player1, as if you had done this:
player1 = Surface["player.png"]
player2 = player1
 
player1.equal? player2                  # => true
 
# So if you modify player2...
player2.set_at( [0,0], [1,2,3,4] )
 
# ... player1 is affected too, because it refers to the same object.
player1.get_at( [0,0] )                 # => [1, 2, 3, 4]
 
# ... and so is Surface["player.png"], because that is the same object too!
Surface["player.png"].get_at( [0,0] )   # => [1, 2, 3, 4]

In cases where you want to get a new object each time, you can use the autoload method instead of []:

player1 = Surface.autoload("player.png")  # => #<Rubygame::Surface:0xa1348ee52>
player2 = Surface.autoload("player.png")  # => #<Rubygame::Surface:0x121b8639c>
 
player1.equal? player2                    # => false
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox