заставить компилятор читать строку как переменную - PullRequest
0 голосов
/ 30 мая 2019

Я пытаюсь воспроизвести случайный аудиоклип в игре, которую я делаю в Phaser 3. Я хочу сыграть одно из следующих действий при наступлении определенного события:

audioBanshee0 = this.sound.add('audioBanshee0',{volume: 0.5});     
audioBanshee1 = this.sound.add('audioBanshee1',{volume: 0.5});     
audioBanshee2 = this.sound.add('audioBanshee2',{volume: 0.5});     
audioBanshee3 = this.sound.add('audioBanshee3',{volume: 0.5});    
audioBanshee4 = this.sound.add('audioBanshee4',{volume: 0.5}); 

Я пробовал следующее:

var ref = Math.floor(Math.random() * Math.floor(5));
const audioBansheeScreech = "audioBanshee" + ref;
audioBansheeScreech.play();

Я получаю сообщение о том, что

audioBansheeScreech.play() не является функцией

, поскольку audioBansheeScreech является строкой.Я могу видеть это с помощью циклов for и if, но я бы предпочел избежать.

1 Ответ

1 голос
/ 30 мая 2019

Может быть легче переместить их в объект, затем вы можете вызвать их, используя строку:

const audioBanshees = {
  audioBanshee0: this.sound.add('audioBanshee0',{volume: 0.5}),
  audioBanshee1: this.sound.add('audioBanshee1',{volume: 0.5}),
  audioBanshee2: this.sound.add('audioBanshee2',{volume: 0.5}),
  audioBanshee3: this.sound.add('audioBanshee3',{volume: 0.5}),
  audioBanshee4: this.sound.add('audioBanshee4',{volume: 0.5})
}

let ref = Math.floor(Math.random() * Math.floor(5));

const audioBansheeScreech = audioBanshees["audioBanshee" + ref];

audioBansheeScreech.play()

Хотя IMO, массив здесь будет более логичным и легче для чтения:

const audioBanshees = [
  this.sound.add('audioBanshee0',{volume: 0.5}),
  this.sound.add('audioBanshee1',{volume: 0.5}),
  this.sound.add('audioBanshee2',{volume: 0.5}),
  this.sound.add('audioBanshee3',{volume: 0.5}),
  this.sound.add('audioBanshee4',{volume: 0.5})
]

let ref = Math.floor(Math.random() * Math.floor(5));

const audioBansheeScreech = audioBanshees[ref];

audioBansheeScreech.play()
...