- Home /
Reliable Order of Components, using GetComponents()
Is there a way to rely on the order of components attached to a given GameObject, when using gameObject.GetComponents()?
For example, I have several 'WhateverActions': MoveObject, TurnObject, ScaleObject, WaitForTime, WaitForEvent, etc. etc. I have been able to assign several of these to a GameObject, as components, and they seem to be in order of appearance. The component I list at the top of the list, is always first. The component I list at the bottom, is always last, and the middle is sorted, etc. If I move a component up in the Inspector, it changes the order of the Array, and so on.
Can this be depended on?
If not... why not? If not, what is my alternative? Do I have to put an integer for each component, and manually make sure they are ordered in the way I want, then GetComponents(), and sort them myself based on that int?
I can't be the first person who wanted to rely on GetComponents and have them be sorted based on the way they are listed in the Inspector... Thank you for any advice and accurate responses.
Answer by aliakbo · Jan 04, 2017 at 01:03 PM
The order of components in in GetComponents is always the order they are, in the inspector. This always holds and if you change the order in the inspector it will change the order in the array.
All unity versions up to now have this behavior.
The last statement isn't true ^^. I can't remember which version actually introduced the ordering of the components in the inspector, but before that the order was kind of random. Though that was a long time ago. I think they added this feature when audio filters were introduced as they rely on the ordering of the components. As far as i remember this was during the 4.x cycle but don't take my word on it. Since 5.0 it's more or less reliably. Though they are still fixing small bugs like:
Ensure correct waking order of components when duplicating a GameObject.
Which is from the 5.0 major update
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Car Positioning System 0 Answers
Implicit type GetComponent call 0 Answers