NullReferenceException error on loading an other scene.

Hi everybody,

I’m new to developing in unity and I’m running into an error at line 5 when I try to call a new scene.

The script is below:

private var hit : RaycastHit;

function Update () 
{
	var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	if(Input.GetMouseButtonDown(0)) 
	{
		if(Physics.Raycast(ray)) 
		{
			if(hit.collider.tag == "playButton") 
			{
				Application.LoadLevel("Level01");
			}
		}
	}	
}

The error that appears is this:

NullReferenceException: Object reference not set to an instance of an object
MenuScene.Update () (at Assets/Standard Assets/Scripts/MenuScene.js:5)

If anyone knows how I fix this, please help me.

Thanks

About the only way you could get a null reference on line 5 is if you don’t have a main camera in the scene. The camera has to be tagged mainCamera.

This works fine:

#pragma strict

    private var hit : RaycastHit;
     
    function Update ()
    {
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Input.GetMouseButtonDown(0))
        {
            if(Physics.Raycast(ray, hit))
            {
                if(hit.collider.tag == "playButton")
                {
                    Application.LoadLevel("Level01");
                }
            }
        }   
    }

Fire,

The tag in the camera works. but now appear another error in line 10:

The error is:

LaunchPad,

Thanks a lot. I changed my code with your and worked fine.