Vector between two objects

This is a very basic question. I want to find the direction vector between two objects. Seems very easy, so I can’t find out why my code does not work.

var obj2: GameObject;
var direction = obj2.transform.position - transform.position;

function Start(){

Debug.Log(obj2.transform.position);
Debug.Log(transform.position);
Debug.Log(direction);
}

The Debug.Log(direction) always returns 0,0,0. Also,the console says that “Object reference not set to instance of an object”. I don’t really know what this means. I made sure that there was an object assigned to the obj2 variable.

If obj2 is not assigned, you will get the result zero, because the operation of assigning the right side of expression will return null exception and the left value will then be set to default. Usually that is prevented with if (obj2 != null).

The error will also happen even if you assign the object but call it before start. You should call the calculation from Start instead and only initialize your variable before.

If you want to get the vector between two points (or two object positions) you should add them, not subtract. Here is a working modification of your code:

#pragma strict
var obj2: GameObject;
var direction: Vector3;

function Start(){
	direction = obj2.transform.position + transform.position;

	Debug.Log(obj2.transform.position);
	Debug.Log(transform.position);
	Debug.Log(direction);
}

And here is my version of your code, you can play with it in scene view while in play mode like here, just drag the GameObject around.

#pragma strict
var obj2: GameObject;
private var direction;

function Update(){
	DoStuff();
	DebugOurStuff();
}

function DoStuff(){			
	if(obj2 != null)
		direction = CalculateMidVector(obj2.transform.position, this.transform.position);
}

function CalculateMidVector(first : Vector3, second : Vector3){
	return first + second;
}

function DebugOurStuff()
{
	Debug.DrawLine(Vector3.zero, obj2.transform.position, Color.blue);
	Debug.DrawLine(Vector3.zero, this.transform.position, Color.cyan);
	Debug.DrawLine(Vector3.zero, direction, Color.green);
}