NullReferenceException: Object reference not set to an instance of an object

I have an GameObject with Box Collider2D (is Trigger) and script addRigidbody attached with this code :

public class addRigidbody : MonoBehaviour {
    Rigidbody2D a;

    void OnTriggerEnter2D(Collider2D coll){
        a = gameObject.AddComponent<Rigidbody2D> ();
        a.angularDrag = 60;
  }
}

This script add the Rigidbody2D to gameobject when it is trigger with the player and set a.angularDrag to 60 but
when the player is trigger with this object, Unity show me this errore message :
NullReferenceException: Object reference not set to an instance of an object
addRigidbody.OnTriggerEnter2D (UnityEngine.Collider2D coll) (at Assets/addRigidbody.cs:9)

The problem is on this line : a.angularDrag = 60;
Why ? The rigidbody is regulary added to gameobject…

Try casting the Rigidbody2D when adding since AddComponent returns an object of type Component, NOT the specific type of component you just added. Since angularDrag is no property of Component you get a null ref.

a = (Rigidbody2D)gameObject.AddComponent<Rigidbody2D> ();

Also it is best practice to name you classes with capital letters first just to be able to distinguish them from properties and alike ( → public class AddRigidbody)

Ok thank you very much ! :wink: