Question by 
               Zuburuburu · May 12, 2017 at 06:46 AM · 
                c#getcomponentcomponentexceptionhandling  
              
 
              How to correctly handle NullReferenceException when using GetComponent<>?
I have tried using:
 TestComponent temp = gameObject.GetComponent<TestComponent >();
                if (temp != null)
                 {
                    //...do things
                  }
 
               However, it gives me an error when I first try to use GetComponent.
I can suppress the error with try/catch block, but what is the way to handle it if I do not have a way to be sure that the object has specific component?
               Comment
              
 
               
              Answer by melsy · Jul 09, 2017 at 11:40 PM
I usually run the null check before the declaration. Like this
if (GetComponent() != null) { rBody2D = GetComponent(); }
this way will it will not try to assign rBody2D to null which throws error.
I keep trying to wrap the code correct but it is not working at all for me right now. Sorry for the shotty formating
Your answer