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:

1 Answer

1

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);
            ...
         }
      }
   }
}

What i was trying to do was make the script place 10 cubes in a random way, but i am new to java so i don't really know what i am doing :D If you could tell me how to do this i would really appreciate it :D

Can you explain how this works then because i am new to java i can right some basic things but i don't quite understand this. :D

Also that script gets an error: Assets/Random.js(14,44): BCE0005: Unknown identifier: 'Block'.

I still have the error : Assets/RandomBlocks.js(26,41): BCE0005: Unknown identifier: 'Block'.

Do you have a var Block : Transform; in the start of your script? Make sure that the same variable have the same name, and please assign the block gameObject to this script through the inspector.