- Home /
Get specific component on gameobject after order in inspector
If i want to get a script according its number in the inspecter, how to i go about that? thinking something along the lines of
GetComponent()
Answer by Kishotta · Mar 11, 2019 at 07:16 PM
MonoBehaviour Components don't really have any concept of what "order" they are in. The Inspector and the Unity Editor collect all of the components and display them in a somewhat predefined order, but that order and logic lives entirely outside your game and can be overridden in the Editor.
What, specifically, are you trying to do? It may be better to make references available in a prefab's inspector (through making them public
or using the [SerializeField]
attribute) and assign the needed references specifically.
In my Game i have a player who has 4 spells. Each as a scrip component attatched to the player. I want to chose one of them of random. so i was thinking if they were 1, 2, 3 and 4 i could just take a random number
If you want randomness then you don't actually need to do what you've asked for. You don't actually care about the order so you could just use GetComponents to make an array of all the components that are Spells, and then pick one randomly from that array.
If you did care about the order then I$$anonymous$$O you'd be better off rethinking your design. For example you could give your player an array of references to spells somehow (I'd probably be looking to make the spells themselves into ScriptableObjects rather than $$anonymous$$onoBehaviours) so that "which slot a spell is in" becomes something you're in control of.
I tried to do something along the lines of an array of script components, but when i started the game it didnt seem to like it. I attatched all the spells to a GO and at the start() did something along the lines of array[0] = this.GetComponent
That's actually not true since Unity version 5.0. With that version they shipped the new audio system and the filter stack system. Those filters rely on the component order in the inspector and since this version we actually have the ability to explicitly re-order the components in the inspector.
So GetComponents does return the components of a gameobject in the order they are specified in the inspector.
However in the case of the OP (having a list of spells), it makes more sense to use some OOP (interfaces, abstract base class) and simply store all relevant instances in an array or List. $$anonymous$$eep in $$anonymous$$d that GetComponents<I$$anonymous$$yInterface>()
actually works and only returns components which implements this interface.
Though for a more specific answer the question need to be more specific.