NullReferenceException Error

Hello! I am creating a ping-pong game to help further my limited knowledge of game programming. I got player movement, launching a ball, and reactions to the ball colliding with a player accomplished. However, I’ve run into a problem with the “Enemy” AI.

What I’m trying to do is base the enemy’s movement on the ball’s x position compared with its own x position (this game is played on the x and z axes). When I try to make a variable to store the ball’s position I encounter this error: “Object reference not set to an instance of an object.” Here’s my code where I encounter the problem:

private Vector3 ballPosition; 	
private Rigidbody ball;
public float moveSpeed = 1.0f;
	
// Use this for initialization
void Start () {
	ball = Launcher.trackBall;
	ballPosition = Launcher.trackBall.position; // Error Here
}

For further explanation of the code, I am making my ball variable equal to my static rigidbody, which is located in the Launcher script. I originally tried to make ballPosition equal to ball.position, but it brought up the same error. Why am I getting this error?

[Edit by Berenger, code formatting]

You shouldn’t use static vars in that situation. I suppose there is only one instance of launcher, so you should find it and access a non-static and properly referenced var trackBall. In other word :

public class Launcher : MonoBehaviour 
{
    // ...
    public Rigidbody trackBall;
    private void Awake()
    {
        trackBall = ??? // Up to you
    }
}

And Wall :

public class Wall : MonoBehaviour 
{
    // ...
    void Start () 
    {
        Launcher launcher = GameObject.FindObjectOfType( typeof(Launcher) ) as Launcher;
        if( launcher == null ) Debug.LogError( "Launcher not found" );
        else
        {
            ball = launcher.trackBall;
            ballPosition = ball.transform.position
        }
    }
}

Now, keep in mind that ballPosition won’t be updated if you leave it at that, but it will keep the original value. You should ball.position whenever you want the actual position.

@hijinxbassist : Yes it does.