Get all Scripts Attached to gameObject

Hello,

Is it possible to get all scripts attached to gameObject without knowing what they are? I basically want to be able to put all the scripts attached to the gameObject into an array.

Thanks

1 Answer

1

its most likely you want only scripts from the game object? if so you can get them as a bunch of mono behaviors, since they all derive from that.

var scripts = gameObject.GetComponents(typeof(MonoBehaviour) as MonoBehaviour[];

just know that this will cast down all the scripts to a mono-behavior, thus will lose all their properties until you re-cast them. you can still access all the properties defined in Monobehaviour.

apparently the order of Get-components is top to bottom.you should pay attention that in order to cast the right scripts(you don’t want to cast a Physics script with an AI script!)

Hope this helps

Yep, this is how it's done. Tip: If you also know that they will not change over time and you only want to ensure you have a reference to them from the start, consider making an editor script that populates the array rather than having to perform it at runtime.

Nice one - thanks!