- Home /
Does GetComponents() return the components in the order that they are displayed in the editor?
My preliminary testing indicates the array returned by calling GetComponents() on a GameObject matches the top-to-bottom order that these components are arranged in the editor. Can anyone confirm that this is correct and/or reliable?
Thanks!
Answer by aldonaletto · Oct 16, 2013 at 11:55 AM
Apparently this is correct, but I would not bet my life on this! Unity may decide to change the order in future versions, since this isn't a documented feature.
Do you have multiple components of the same type attached to your game object and want to access each one independently? If so, a common solution for components added at runtime is to get a reference to each one from AddComponent - kind of:
private var audio1: AudioSource;
private var audio2: AudioSource;
private var audio3: AudioSource;
function Start(){
audio1 = gameObject.AddComponent(AudioSource);
audio2 = gameObject.AddComponent(AudioSource);
audio3 = gameObject.AddComponent(AudioSource);
}
Unfortunately, there's no general solution for components added in the Editor. For AudioSources (the most frequent multiple component), however, the priority field may be used as a temporary ID: you can set the first AudioSource priority to 128 in the Inspector, the second to 129, and so on; at Start, get the AudioSources in an array, identify each one and, if necessary, set their priority values to whatever they should be (the field priority is used only when there are too many AudioSources playing at the same time, and small variations around the default 128 usually don't make any difference.
Thanks for your help!
The reason I'm asking is that I want to expose some basic control over gameobjects to designers. I was considering using components, arranged in order, as a way of chaining behaviours - eg, a $$anonymous$$oveBehaviour, a WaitBehaviour, another $$anonymous$$oveBehaviour, etc.
As this doesn't look to be official or supported, looks like I can't rely on using the editor in this way. Back to the drawing board!
$$anonymous$$aybe a custom editor is the best solution in your case.
Damn,the priority principal is just so obvious I did not see it. I have often wondered how to get a particular AudioSource when you have many attached, but got stuck on the fact that you cannot name a component and always ended up with a children and drag and drop. Sometimes obvious just does not strike...
Your answer
Follow this Question
Related Questions
How to make an Array equal the Components of an Instantiated GameObject 1 Answer
Bad array declaration: Why won't this compile? 2 Answers
List.Sort with IComparer 2 Answers
Array loads in wrong order 3 Answers
Same script on multiple objects 1 Answer