NullReferenceException: Object reference not set to an instance of an object Random.OnGUI () (at Assets/Random.js:25)

var Block : Transform;
var textureIndicator : GUITexture;
//private var textures = new Array() ;
//private var selectedTexture : int;

function start(){
//textures = Resources.Load.A11("Textures", Texture);
}

function update () {






}
function OnGUI(){
if (GUI.Button (Rect (20,40,80,20), "Start")){
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;

for(counter=1;counter<=10;counter++){
var newBlock : Transform = Instantiate (Block, hit.collider.transform.position+hit.normal.normalized, Quaternion.identity);
//newBlock.renderer.material.mainTexture = textures [selectedTexture];
newBlock.tag = "Block";

}
    

}
}

I have that error i dont know what it means, if anyone could help it would make me happy :smiley:

function OnGUI(){
if (GUI.Button (Rect (20,40,80,20), “Start”)){
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit; //this is null

      for(counter=1;counter<=10;counter++){
         //hit is still null when you try to use it
         var newBlock : Transform = Instantiate (Block, hit.collider.transform.position+hit.normal.normalized, Quaternion.identity);
         ...
      }
   }
}

The way you declare the ray and hit means that you need to know what object you are clicking on; however, when you put it in a GUI.Button(), it limits where you will be clicking on (the Rect containing the button). Your logic doesn’t make sense to me, however this is just a opinion from me, you know the best what you are doing.

To fix the null-ref-exception, do a Physics.Raycast() before you use the hit.

function OnGUI(){
   if (GUI.Button (Rect (20,40,80,20), "Start")){
      var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      var hit: RaycastHit;

      if( Physics.Raycast( ray, hit ) ) {
         for(counter=1;counter<=10;counter++){
            var newBlock : Transform = Instantiate (Block, hit.collider.transform.position+hit.normal.normalized, Quaternion.identity);
            ...
         }
      }
   }
}