NullReferenceException in C#

Hi, guys! I’m starting to develop in Unity and I came across this error and I don’t know how to solve it:
"NullReferenceException: Object reference not set to an instance of an object
BulletSetup.Start () (at Assets/Scripts/BulletSetup.cs:54)"

BulletSetup.cs

public class BulletSetup : MonoBehaviour {

    private float xVelocity;
    private float yVelocity;
    private float shotAngle;

    private float xWindVelocity;
    private float yWindVelocity;
    private float windAngle;

    private float xAirDrag;
    private float yAirDrag;
    private float airDragAngle;

    private int playerTurn;
    public GameObject velocityInfo;
    public GameObject windInfo;

    void Start () {
        playerTurn = windInfo.GetComponent<GameSetup> ().playerTurn;

        xWindVelocity = windInfo.GetComponent<GameSetup> ().xWindSpeed;
        yWindVelocity = windInfo.GetComponent<GameSetup> ().yWindSpeed;

        xAirDrag = windInfo.GetComponent<GameSetup> ().xAirDrag;
        yAirDrag = windInfo.GetComponent<GameSetup> ().yAirDrag;

        shotAngle = shotAngle * Mathf.Deg2Rad;

        if (playerTurn == 1) {
            Debug.Log (playerTurn);

            xVelocity = velocityInfo.GetComponent<Player1Setup> ().shotVelocity;
            shotAngle = velocityInfo.GetComponent<Player1Setup> ().shotAngle;

            shotAngle = shotAngle * Mathf.Deg2Rad;

            xVelocity = xVelocity + xWindVelocity - xAirDrag;
            yVelocity = Mathf.Tan (shotAngle) * xVelocity + yWindVelocity - yAirDrag;
           
            rigidbody2D.AddForce (new Vector2 (xVelocity, yVelocity));

        }

        if (playerTurn == 2) {
            Debug.Log (playerTurn);

            xVelocity = velocityInfo.GetComponent<Player2Setup> ().shotVelocity;
            shotAngle = velocityInfo.GetComponent<Player2Setup> ().shotAngle;
           
            shotAngle = shotAngle * Mathf.Deg2Rad;

            xVelocity = -xVelocity + xWindVelocity + xAirDrag;
            yVelocity = Mathf.Tan (shotAngle) * xVelocity + yWindVelocity - yAirDrag;

            rigidbody2D.AddForce (new Vector2 (xVelocity, yVelocity));
        }
    }
}

I don’t understand why it works for playerTurn == 1 but it does not work for playerTurn == 2.

It looks like your trying to access the component Player2Setup but you get null if it’s not attached to velocityInfo.

Probably what RSG sayed…try to check if your Player2Setup component is not null, something like this:

        if (playerTurn == 2)
            Debug.Log (playerTurn);

        Player2Setup p2 = velocityInfo.GetComponent<Player2Setup> ();

        if(p2 == null)
            Debug.LogError("Player 2 Component is null!!");
        else
        {
            //Your code here...
        }

Thanks, velocityInfo was receiving the GameObject of Player 1 and Player 1 indeed doesn’t have Player2Setup.