NullReferenceException: Object reference... when trying to instantiate an object

I’m trying to get an object to instantiate upon click. When I try to test out my script i get

NullReferenceException: Object reference not set to an instance of an object
blockSpawn.Update () (at Assets/scripts/blockSpawn.js:10)

as an error.

I’ve been trying to fix this for around 5 hours now with no luck… I’m new to this so I may be missing something simple. I appreciate any help with this issue.

    var block : GameObject;
   
     function Start(){
    	       } 
     
    function Update () {

    var mousex = Input.mousePosition.x;
    var mousey = Input.mousePosition.y;
    var ray = Camera.main.ScreenPointToRay (Vector3(mousex,mousey,0));
     
    var hit : RaycastHit;
     
    if (Physics.Raycast (ray, hit, 200)) {
     
    }
    if ( Input.GetMouseButtonDown(0) )
   {
    var createBlock = Instantiate(block, hit.point, Quaternion.identity);  
   }
    else {}
   
    
 }

Thanks again for the help guys!

The hit in your code can be null.
The
if (Physics.Raycast (ray, hit, 200))
check is there so that you’d only do stuff if the raycast hits something, but you have left the of clause empty and try to do stuff upon mouse click even when the ray doesn’t hit anything.

If you only want to do stuff when the mouse is clicked, then that should be your first condition.

    if ( Input.GetMouseButtonDown(0) )
   	{
	    var hit : RaycastHit;
	    if (Physics.Raycast (ray, hit, 200)) 
	    {
		    var createBlock = Instantiate(block, hit.point, Quaternion.identity);  
	    }
   	}

P.S. If you just want to create an object on the screen where the player clicked/touched, you don’t need to raycast. Your code checks whether the click hits another object (with a collider) on the screen and tries to create a new object where the click hits the pre-existing object.