Multi similar script Components same game object

How to access a script on a gameobject that contains multiple components with similar instances of a script? I haven’t done this before so thats why i’m asking! i want to access one of them


One way to do it, since all the scripts you attach to your objects inherit from MonoBehaviour, this means you can do something manual like (just showing variety of ways):

MonoBehaviour[] mbs = GetComponents<MonoBehaviour>();
foreach (MonoBehaviour mb in mbs)
  if (mb is AtlasController)
    // do something

Other shorter and better way:

AtlasController[] arr = GetComponents<AtlasController>();

and then filter the array.

Note that this will work on the gameObject that this script will attached to, so all these writings are the same:

AtlasController[] arr = GetComponents<AtlasController>();
AtlasController[] arr = gameObject.GetComponents<AtlasController>();
AtlasController[] arr = this.gameObject.GetComponents<AtlasController>();

I’d just use the first one. If you wanted to fetch the components from another object, you’d simply do:

AtlasController[] arr = otherGameObject.GetComponents<AtlasController>();