Assigning a transform using the ray cast collider.

Hey guys,

I want the GUI buttons I make to rotate the parent of the object I select, and I am having trouble getting the transform of the object I click on using raycast. I have attached my code in the hopes someone has an idea of what I am doing wrong.

The error I keep getting is : (NullReferenceException: Object reference not set to an instance of an object
Select2.OnGUI () (at Assets/Select2.js:24)

//var capsule : Transform;
var clicked : boolean = false;
var hit : RaycastHit;

function Update() {

	var capsule : Transform;
	
    if(Input.GetMouseButtonDown(0) &&
       collider.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit,
                        Mathf.Infinity)) {
     
         capsule = hit.collider.GetComponent(Transform);
         
    }
}
 
  function OnGUI()
        {
        
        var capsule = hit.collider.GetComponent(Transform);
		var someText = "Turn Left";
		var otherText = "Turn Right";
              
			if (GUI.Button(new Rect(20, 50, 100, 20), someText)){
				//capsule = hit.collider.GetComponent(Transform);
				capsule.parent.transform.Rotate (0, 0, 45, Space.World);
				}
               
			else if (GUI.Button(new Rect(850, 50, 100, 20), otherText)){
				//capsule = hit.collider.GetComponent(Transform);
				capsule.parent.transform.Rotate (0, 0, -45, Space.World);
				}
  
        }

Hit has not been set until you set it.

You need to check it first:

if ( hit ) { /do all your stuff here/ }

Alright, back up a bit.

In all programming, whenever (every time) you use any object which can be null, you must FIRST be sure that the object is not null. If you don’t check, you’ll have errors - period.

The simplest and least error-prone way to do this is:

if ( object ) {
  if ( object.child ) {
    if ( object.child.member ) {
      object.child.member.DoSomethin();
    }
    object.child.DoSomething();
  }
  object.DoSomething();
}

Often, you can be assured that the object is not null due to code flow - for instance:

function OnTriggerEnter( other : Collider ) {
  // other cannot possibly be null
  other.SendMessage("HitBy" + name);
}

Or:

function Setup() {
  object = new Thingy();
  object.DoSomething();
}

So for your specific problem, you have a couple of things which can be null - capsule, hit.collider, someText, and otherText. You know someText and otherText aren’t null - you just created them. You also know that you only have a capsule when hit.collider is not null. And there’s no reason to show the buttons if you don’t have a capsule.

So: you can put most of the OnGUI function into that check for hit.collider and then be guaranteed that capsule is not null, or you can check for null capsule before trying to turn it.