Calling function from another script

I have problem calling function from other script. It shows me this warning:

Assets/Moje/ArrowDMG.js(15,37): BCW0028: WARNING: Implicit downcast from ‘UnityEngine.Component’ to ‘EnemyHealth’.

ArrowDMG.js

 #pragma strict
    
    
    function Start () {
    
    }
    
    function Update () {
    
    }
    
    function OnCollisionEnter (other : Collision){
    
    	var eh : EnemyHealth;
    	eh = gameObject.GetComponent("EnemyHealth");
    
    if(other.gameObject.tag == "Enemy") {
        eh.AdjustCurrentHealth(-5);
    	Destroy(gameObject);
    	}
    
    }

EnemyHealth.js

var currentHealth = 100;
var maxHealth = 100.0;

var healthBarLength = 0.0;

function Start () {

	AdjustCurrentHealth(0);

}

function OnGUI() {

	GUI.Box(new Rect(10, 10, healthBarLength, 20), currentHealth + "/" + maxHealth);
	
}

function AdjustCurrentHealth (adj : int) {

	currentHealth = currentHealth + adj;

	if(currentHealth < 0) 
		currentHealth = 0;
	if(currentHealth > maxHealth) 
		currentHealth = maxHealth;
	if(maxHealth < 1)
		maxHealth = 1;
		
	healthBarLength = (Screen.width / 2) * (currentHealth / maxHealth);
	
	}

1 Answer

1

The problem is here:

eh = gameObject.GetComponent("EnemyHealth");

Remove the quotation marks:

eh = gameObject.GetComponent(EnemyHealth);

With the quotation marks, the compiler does not know at compile time the type returned by GetComponent(), so it defaults to Component.

Thank you very much. But now i have one more problem. When i play game, it sends me error NullReferenceException: Object reference not set to an instance of an object ArrowDMG.OnCollisionEnter (UnityEngine.Collision other) (at Assets/Moje/ArrowDMG.js:18)

The code as you have it now assumes the EnemyHealth script is on the same game object as the ArrowDMG script. Is that true? Given the names, I expect not.

I suspect he wants to do eh = other.gameObject.GetComponent(EnemyHealth);

EnemyHealth is script on the other object, and when arrow hits it, I want to deduct 5 health.

Then you need to get the component from the other game object. Something like: eh = other.collider.GetComponent(EnemyHealth);