I thought I had references in AS3 figured out, but the following behavior puzzles me:
// declarations for named individual reference later on
var myAmbientSound:Sound;
var myAmbientSoundLocation:String = "http://ambient_sound_location";
var myPeriodicSound:Sound;
var myPeriodicSoundLocation:String = "http://periodic_sound_location";
var myOccasionalSound:Sound;
var myOccasionalSoundLocation:String = "http://occasional_sound_location";
// for iterating through initialization routines
var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
var mySoundLocation:Array = [myAmbientSoundLocation, myPeriodicSoundLocation, myOccasionalSoundLocation];
// iterate through the array and initialize
for(var i:int = 0; i < mySoundArray.length; i++) {
mySoundArray[i] = new Sound();
mySoundArray[i].load(new URLRequest(mySoundLocation[i]));
}
At this point, I'd think that mySoundArray[0]
would reference the same object as myAmbientSound
; however, accessing myAmbientSound
throws a null pointer exception, while mySoundArray[0]
works as expected and references a Sound
object. What am I misunderstanding here?
It is more like java reference variables than C pointers.
var myAmbientSound:Sound;
var myPeriodicSound:Sound;
var myOccasionalSound:Sound;
//these variables are not initialized and hence contain null values
Now you create an array containing the current values (null) of these variables
var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
The array now contains three nulls [null, null, null]
, and not three pointers to Sound
objects as you expect it to contain.
Now when you call mySoundArray[0] = new Sound();
a new Sound
object is created and its address is assigned to the first location of the array - it doesn't modify the myAmbientSound
variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With