Is the only option for using GetComponent() to get more than one component of the same time GetComponents()?
For example, if I have several audio files I want to play depending on the scenario, do I have to:
public class ExampleClass : MonoBehaviour {
public AudioSource[] audios;
void Example() {
audios = GetComponents<AudioSource>();
if (_condition_)
audios[0].Play();
else
audios[3].Play();
}
}
If that’s the case, I seem to only be receiving the audio file for the first AudioSource component (audios[0]) and none of the others. Does it not pass in order of component in the inspector for the GameObject? Is there no way to call by audio name or something? If not, can someone explain why, as this seems so senseless to me! Thank you very much!
Well, GetComponents will always return an array, but that should not restrict you. You can use a dictionary instead. Instead of using multiple sources, you might want to use one source and multiple clips like so:
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class ExampleClass : MonoBehaviour
{
public AudioSource source;
public List<AudioClip> clips = new List<AudioClip>();
private Dictionary<string, AudioClip> clipsByName;
void Example()
{
source = GetComponent<AudioSource>();
// Either seek directly from the list
source.clip = clips.FirstOrDefault(c => c.name == "ClipName");
// Or use a dictionary
clipsByName = clips.ToDictionary(c => c.name, c => c);
AudioClip clip;
if (clipsByName.TryGetValue("ClipName", out clip))
{
source.clip = clip;
}
}
}
GetComponents() will get all audio source components on the game object attached to this script. If there is only one audio source then it will only have one in the array. They will enter the array in order in the inspector.
By the way, check if the audio source is null before trying to access its fields.