Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Passing a any component as a parameter

Discussion in 'Scripting' started by SD2020_, Sep 24, 2017.

  1. SD2020_

    SD2020_

    Joined:
    Nov 3, 2015
    Posts:
    107
    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.
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    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<T>.

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

    Code (csharp):
    1. TComponent AddComp<TComponent>(GameObject go) where TComponent : UnityEngine.Component, new()
    2. {
    3.     return go.AddComponent<TComponent>();
    4. }
    5.  
    6. //or
    7. Component AddComp(GameObject go, Type componentType)
    8. {
    9.     // either handle type validation or let Unity's AddComponent handle it, as it does this either way
    10.     // I'd just let Unity handle it and simply do
    11.     return go.AddComponent(componentType);
    12. }
    13.  
    Note that the return value (TComponent / Component) is optional, you could also make it void if you don't really need that functionality.
     
    SD2020_ likes this.
  3. SD2020_

    SD2020_

    Joined:
    Nov 3, 2015
    Posts:
    107
    That it perfect thank you very much!

    I will give this a try ASAP!