title: Unity: Generic Method to get or add a component
body: <p>Every time I make a new Script in Unity, I always end up doing a bunch of checks for any components my script depends on, like:</p>
  
  <pre><code>SpriteRenderer sr = gameObject.GetComponent&lt;SpriteRenderer&gt;();
  
  if(sr == null)
        sr = gameObject.AddComponent&lt;SpriteRenderer&gt;() as SpriteRenderer;
  </code></pre>
  
  <p>So I decided to play around and make a generic method to do this with any Component, and I came up with the following code, which I simply added right to my own new Script.</p>
  
  <pre><code>  T GetOrAddComponent&lt;T&gt;() where T : Component
      {
          T component = gameObject.GetComponent&lt;T&gt;();
  
          if (component == null)     
              component = gameObject.AddComponent&lt;T&gt;() as T;
  
          return component;
  
      }
  </code></pre>
  
  <p>I've tried it and the function works well, but I'm wondering if there is any major downside to this approach, or if there is some other better way to complete the same task, possibly using a existing method I am unaware of or by creating the method in some other way. </p>