1

我在链接属性中设置了 15 个名为“Sound1”、“Sound2”等的声音。我想在循环中动态引用它们。例如,而不是

currentMusic = new Sound2();

我该怎么做

currentMusic = new ("Sound" + i)();

或者有什么更好的方法来做到这一点?

4

2 回答 2

1

使用与在运行时加载影片剪辑或字体相同的过程。

假设您的库中有声音导出为“sound_0”、“sound_1”、...、“sound_9”等:

for(var i:uint = 0; i < 10; i++)
{
    var soundClass:Class = getDefinitionByName("sound_" + i.toString()) as Class;
    var sound:Sound = new soundClass();
}
于 2012-08-16T10:18:18.693 回答
1

将生成的类名存储到变量中,从应用程序域中检索类并实例化新对象。小心例外!

var soundClassName:String = "Sound" + i;
var soundClass:Class;
var sound:Sound;

try {
    soundClass = getDefinitionByName(soundClassName) as Class;
    sound = new soundClass();
} catch (re:ReferenceError) {
    trace("Class '" + soundClassName + "' not found");
} catch (te:TypeError) {
    trace("Unable to instantiate the sound object");
}
于 2012-08-16T10:20:06.010 回答