Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Calling a generic function not working

Discussion in 'Scripting' started by digital_monk, Oct 26, 2020.

  1. digital_monk

    digital_monk

    Joined:
    Jun 2, 2017
    Posts:
    10
    I'm new to Unity and wanted to experiment with creating generic functions.

    So for learning purpose, I created a static method which adds a component to a passed gameobject and returns the component itself. How usable the function is questionable, but the idea is to learn about generic functions.

    Code (CSharp):
    1.     public static T GetAddedComponent<T>(GameObject go, T component){
    2.         go.AddComponent(component.GetType());
    3.         return go.GetComponent<T>();
    4.     }
    This seems ok to me, but again I'm really not sure if this is the right way to do it. The problem I'm having is when calling the method:

    Code (CSharp):
    1. .   SpriteRenderer spriteRenderer = GetAddedComponent(enemy1, SpriteRenderer);
    This is the error:

    'SpriteRenderer' is a type, which is not valid in the given context 


    How do I go about this?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,723
    You don't need to pass the generic type in as a parameter. That's what the <T> bit is for.

    The way to write this generically is:
    Code (CSharp):
    1. public static T GetAddedComponent<T>(GameObject go) where T : Component {
    2.         go.AddComponent<T>();
    3.         return go.GetComponent<T>();
    4.     }
    However, there's not really any point to this function because
    AddComponent<T>()
    already returns the newly created component. (In fact this implementation has a bug because GetComponent might not return the same component you just added). So you could simplify your method to just:
    Code (CSharp):
    1.     public static T GetAddedComponent<T>(GameObject go) where T : Component {
    2.         return go.AddComponent<T>();
    3.     }
    Or in fact just delete this function and use AddComponent<T>() directly.
     
    digital_monk likes this.
  3. digital_monk

    digital_monk

    Joined:
    Jun 2, 2017
    Posts:
    10
    Great, I understand what I was doing wrong. Thanks!

    As I mentioned before - How usable the function is questionable, but the idea is to learn about generic functions.