What's the easiest way to get multiple components?

Yep that’s the question, 3D game btw. I don’t need to provide more information right? Just a question.

Any “find” or search is always contextual. Where and when are you looking? Did you leave your glasses in my car? Or are you pretty sure they’re inside your house somewhere? Or maybe they fell out of your pocket on your last international flight? Your search strategy would be quite different for those three things.

Some runtime answers might be:


GetComponents<T>()

GetComponentsInChildren<T>()```

At Editor time it would be methods in the ```AssetDatabase``` class most likely, but you could use other techniques too.

Sorry, I don’t quite get it, I have two almost the same script named and . I don’t know how to get both of the components. This is my code.

Target target = hit.transform.GetComponent<Target>();

I only can get one of the component, but can’t get the other one.

There’s no reliable way to use GetComponent() to get two things on one object, if you care about which is which.

You can get ALL the things with GetComponents() but they are returned in undefined order.

If possible it is always best to drag stuff into public fields on the prefab or in the scene. It will work 100% of the time. When two components are on a single object you can lock the inspector (tiny lock upper right corner) and drag each one from a second inspector window (which you can open from right-clicking the tab).

ok, thx a lot

could add custom script there to work as a cache or interface for many components, like:
MyComponents.cs:
// public vars or as getters/setters
public Target1 target1;
public Target2 target2;
void Awake()
// get components in awake or only after requested

Hmm, what about the get components part, can’t figure out how to write it

I wrote extension method like this before:

public static Component[] GetAllComponents<T1, T2, T3, T4>(this GameObject gameObject)
    {
        List<Component> components = new List<Component>();
        foreach (Component component in gameObject.GetComponents<Component>())
        {
            if (component.GetType().IsEquivalentTo(typeof(T1))
                || component.GetType().IsEquivalentTo(typeof(T2))
                || component.GetType().IsEquivalentTo(typeof(T3))
                || component.GetType().IsEquivalentTo(typeof(T4)))
            {
                components.Add(component);
            }
        }
        return components.ToArray();
    }
1 Like

Wow, thank a lot! :):):slight_smile: