Passing a any component as a parameter

Hi there,

Im looking for a way to pass any sort of component into a function as a parameter.

Example:

AddComp(Light, m_GameObject);

void AddComp(component _comp, GameObject m_pGameObject)
{
m_pGameObject.AddComponent(_comp);
}

Is something like this possible to do? Trying to do it for an editor script.

You cannot use AddComponent with an already existing instance. You have to provide a type, which is basically already handled by AddComponent(Type t) and AddComponent.

Frankly, I’m not sure if this makes some sense, but your method would rather look like (written in the browser, sorry for typos):

TComponent AddComp<TComponent>(GameObject go) where TComponent : UnityEngine.Component, new()
{
    return go.AddComponent<TComponent>();
}

//or
Component AddComp(GameObject go, Type componentType)
{
    // either handle type validation or let Unity's AddComponent handle it, as it does this either way
    // I'd just let Unity handle it and simply do
    return go.AddComponent(componentType);
}

Note that the return value (TComponent / Component) is optional, you could also make it void if you don’t really need that functionality.

1 Like

That it perfect thank you very much!

I will give this a try ASAP!