I want to have an object detect when a player collides with it and play a specific audio piece from an array. I got the trigger to play random audio from the array on startup, but i want to have a specific audio play from the array when the player collides with it.
UPDATE: I figured out why my player didn’t collide with the trigger: I stupidly didn’t capitalize the “o” on “OnTriggerEnter”.
HOWEVER I still have not found out how to select 1 specific audio piece to play from an array.
Here is my updated code:
using UnityEngine;
using System.Collections;
public class AudioEventTriggerPlay : MonoBehaviour {
public int PlayAudioValue;
public bool PlayOnlyOnce;
//array of audio i want to have play
public AudioClip[] AvailableAudioCanPlay;
AudioSource PlayAudio;
// Use this for initialization
void Start () {
PlayAudio = GetComponent<AudioSource>();
}
//check if player collides with this object
void OnTriggerEnter(Collider Other){
if (Other.gameObject.name == "Player"){
//debug check if player collided with the trigger
print("The player touched me! D:");
switch (PlayAudioValue){
case 0:
Debug.Log("Announcer tutorial string 1");
KillAfterPlay();
break;
case 1:
Debug.Log("Announcer tutorial string 2");
KillAfterPlay();
break;
case 2:
Debug.Log("Announcer tutorial string 3");
KillAfterPlay();
break;
case 3:
Debug.Log("Announcer tutorial string 4");
KillAfterPlay();
break;
case 4:
Debug.Log("Unreserved slot");
KillAfterPlay();
break;
case 5:
Debug.Log("Unreserved slot");
KillAfterPlay();
break;
case 6:
Debug.Log("Unreserved slot");
KillAfterPlay();
break;
case 7:
Debug.Log("Unreserved slot");
KillAfterPlay();
break;
case 8:
Debug.Log("Unreserved slot");
KillAfterPlay();
break;
default:
Debug.Log("Error: No available cases left or value is out of range!");
break;
}
//play audio from array Element 0
/*if (PlayAudioValue == 0){
PlayAudio.clip = AvailableAudioCanPlay[Random.Range(0, AvailableAudioCanPlay.Length)];
PlayAudio.Play();
KillAfterPlay();
}
//play audio from array Element 1
if (PlayAudioValue == 1){
PlayAudio.clip = AvailableAudioCanPlay[Random.Range(0, AvailableAudioCanPlay.Length)];
PlayAudio.Play();
KillAfterPlay();
}
//play audio from array Element 2
if (PlayAudioValue == 2){
PlayAudio.clip = AvailableAudioCanPlay[Random.Range(0, AvailableAudioCanPlay.Length)];
PlayAudio.Play();
KillAfterPlay();
}
//play audio from array Element 3
if (PlayAudioValue == 3){
PlayAudio.clip = AvailableAudioCanPlay[Random.Range(0, AvailableAudioCanPlay.Length)];
PlayAudio.Play();
KillAfterPlay();
}*/
}
}
// when bool PlayOnlyOnce is checked
void KillAfterPlay(){
if (PlayOnlyOnce == true){
//destroys self when audio is finished playing
Destroy(gameObject, AvailableAudioCanPlay.Length);
}
}
}