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)

What you’re asking for can be done by reflection, as done here: C# Reflection - Get field values from a simple class - Stack Overflow . 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>();
	}

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;
	}
	
}