Getting a error when i access my health script.

when I access my other script with the attack function I get a error of nullreference object not set to an instance of an object. here is the code.

function Attack(){
	var EnemyHeathScript : EnemyHeath;
	EnemyHeathScript = GetComponent("EnemyHeath");
	EnemyHeathScript.AdjustCurrentHealth(-10);
}

and this is the code im accessing

function AdjustCurrentHealth(adj : int){
	curHealth += adj;
	
	if(curHealth < 1){
		curHealth = 0;
	}
	if(curHealth > maxHealth){
		curHealth = maxHealth;
	}
	if(maxHealth < 1){
		maxHealth = 1;
	}
	healthBarLeangth = (Screen.width / 2) *(curHealth / maxHealth);
}

Perhaps try dubble checking if the script is called EnemyHeath or if it's EnemyHealth. It looks like the error is being thrown by the GetComponent part of your code

I went and fixed the spelling error on them but that didn't fix anything still throwing the same error. This is the line it is pointing me toEnemyHeathScript.AdjustCurrentHealth(-10);

So just to make sure, do you still get the error if you use this? function Attack(){ var EnemyHealthScript : EnemyHealth; EnemyHealthScript = GetComponent("EnemyHealth"); EnemyHealthScript.AdjustCurrentHealth(-10); }

yes same error here is the total error NullReferenceException: Object reference not set to an instance of an object PlayerAttack.Attack () (at Assets/scripts/PlayerAttack.js:18) PlayerAttack.Update () (at Assets/scripts/PlayerAttack.js:12)

I don't see anything wrong with the Attack() function. [[GetComponent][1]] The NullReferenceException error occurs when the script can't be found. Are both scripts on the same game object? [1]: http://docs.unity3d.com/Documentation/ScriptReference/Component.GetComponent.html

1 Answer

1

Ah well you have to add a reference to the enemy object so it knows where to look:

var EnemyObject : GameObject;

function Attack(){
  var EnemyHealthScript : EnemyHealth;
  EnemyHealthScript = EnemyObject.GetComponent("EnemyHealth");
  EnemyHealthScript.AdjustCurrentHealth(-10);
}

thank you.