- Home /
enable components with same name via script...
Hy guys ! I have this question: Is possible active two components with same name via script in time order ? Example: Play the level and the first AudioSource is enabled, after 5 second the 2nd AudioSource is enabled, it is possible ? I have created an object in my scene with two audio source like this
Thank you guys !
Answer by CarterG81 · Feb 16, 2017 at 11:16 PM
Add a Manager script which both stores the references to these components & contains functions to manipulate them.
class AudioComponentManager.cs
[SerializeField] AudioSource firstAudio; //Assign these in the Inspector
[SerializeField] AudioSource secondAudio;
void EnableThem()
{
firstAudio.SetActive(true);
//wait five seconds (Coroutine? In Update?)
//secondAudio.SetActive(true);
}
This is pretty much how Unity always works. "Manager" scripts are very useful. Especially considering that many methods don't return Inactive components.
Answer by hexagonius · Feb 16, 2017 at 08:36 PM
It is:
AudioSource[] sources = GetComponents<AudioSource>();
will return an array, with AudioSources in order, so sources[0]
is the first, sources[1]
the second and so on.
no it not found :( public GameObject audio$$anonymous$$anager; AudioSource[] sources = audio$$anonymous$$anager.GetComponents ();
but sources[0].enabled = true; not found :(
GetComponent and FindObject methods do not work for objects are SetActive(false) or components that aren't already enabled. To do this, you would need to obtain the references, then disable on start/awake/enable, and then you'll have your usable references. Also you should always use an iteration to go through an array. For example.
for (int i = 0; i < sources.Length; i++)
{
if (sources[i] != null)
{
sources[i].enabled = true;
}
}
Your answer
Follow this Question
Related Questions
How can I have two scripts in the animator panel ? 1 Answer
Audio Clip Playing every frame 2 Answers
Audio Mixer exposed parameter path error? 0 Answers
Cannot access AudioSource from within function 0 Answers
Best way for sound and reload? 2 Answers