static var error when var == null

I have this script reading a static var from another script and it works just fine when target is selected. The code below is attached to a homing missile.

function Awake(){

	TargetingGUIEnemy = GameObject.Find("TargetingGUIEnemy");
	TargetEnemy = TargetingGUIEnemy.GetComponent("TargetEnemy");
	Target = TargetEnemy.Target.transform;
	
}

But when I have nothing selected (Target == 0 in that other script) I get an error.

Does anyone have an idea how to mend this?

try this:

function Awake(){
	if (TargetEnemy.Target) {
		TargetingGUIEnemy = GameObject.Find("TargetingGUIEnemy");
		TargetEnemy = TargetingGUIEnemy.GetComponent("TargetEnemy");
		Target = TargetEnemy.Target.transform;
	}
}

Variables should be in camelCase while functions are in CamelCase.

You can’t access members of null (since it isn’t)

You’re trying to access null.transform which is impossible.

Use

if ( targetEnemy.target ) target = targetEnemy.target.transform;

Edit @JM: You can’t use targetEnemy before it’s given meaningful information. At the start of the function in this particular case it can only contain ‘garbage’ data.

Wow, that was fast! :smile:

Thx guys!

@Vicenti: Yes, your remark stands. That is the very reason I got confused. Here is the working code:

function Awake(){

	TargetingGUIEnemy = GameObject.Find("TargetingGUIEnemy");
	TargetEnemy = TargetingGUIEnemy.GetComponent("TargetEnemy");
	
	if (TargetEnemy.Target){
	Target = TargetEnemy.Target.transform;
	}
}

Very elegant. Thank you once again.