- Home /
Access all variables of type within a C# script
Is it possible to access all variables of a given type within a C# script?
Specifically, I'd like to take a whoooole bunch of AudioClip variables and, in the Start() function, put them all into an array (without having to manually add every AudioClip). Basically, the working equivalent of:
foreach (AudioClip clip in this)
Answer by Jamora · Jul 10, 2013 at 11:44 PM
What you're asking for can be done by reflection, as done here: http://stackoverflow.com/questions/7649324/c-sharp-reflection-get-field-values-from-a-simple-class . However, you do need to assign the AudioClips to the variables either in code or in the inspector.
A simpler way would be to select all AudioClips you want added, drag them all at once to the GameObject, then in a script in the same GameObject do:
AudioClip[] audioClips;
void Start(){
audioClips = gameObject.GetComponents<AudioClip>();
}
Answer by tw1st3d · Jul 10, 2013 at 11:30 PM
Hmm. Well, I don't think you can do what you added in for code, but I know one thing you can do.
using System.Collections;
using UnityEngine;
public class YourClassName
{
private AudioSource[] sources;
public void Start()
{
SetSources(new AudioSource source1, new AudioSource source2);
}
public void SetSources(AudioSource[] SourceList)
{
sources = SourceList;
}
}