Area of effect

Hey!
I am working on a tower defence kind of game and I am trying to make projectiles deal damage in an area. When the projectiles hit the targets I get: “Object reference not set to an instance of an object”. Here is my script:

public var rad : float = 10;
private var center : Vector3; 
 
private var hitTarget : GameObject;

public var damage : float = 10;
function Update () {

}
function OnCollisionEnter(hitTarget : UnityEngine.Collision){ 
	if(hitTarget.gameObject.tag == "Enemy"){
	var objectHit = hitTarget.gameObject; 
	//Callhealth = GameObject.Find(objectHit).GetComponent(Health);
	objectHit.GetComponent(Health).applyDMG(damage);
	areaOfEffect(transform.position, 10);
	//objectHit.SendMessage("applyDMG", 10);
		//Callhealth.applyDMG(damage);
		Destroy(this.gameObject);
	}
	
}
function areaOfEffect(center : Vector3, rad : float){
	var hitEnemies : Collider[] = Physics.OverlapSphere(center, rad); //från mittpunkten och rad:s värde utåt 
	
	for(var x=0; x < hitEnemies.Length; x++){
		hitEnemies[x].GetComponent(Health).applyDMG(damage);
	}
}

Any kind of help would be much appreciated! :slight_smile: Thanks in advance.

You need to do a check to make sure that your Health Component is actually attached to the object that you’ve found; the ground, for instance, shouldn’t have one…right? :slight_smile:

function OnCollisionEnter(hitTarget : UnityEngine.Collision)
{
    if(hitTarget.gameObject.tag == "Enemy")
    {
        var objectHit = hitTarget.gameObject; 
        //Callhealth = GameObject.Find(objectHit).GetComponent(Health);
        var health = objectHit.GetComponent(Health);
        if (health != null)
        {
            health.applyDMG(damage);
            areaOfEffect(transform.position, 10);
            //objectHit.SendMessage("applyDMG", 10);
            //Callhealth.applyDMG(damage);
            Destroy(this.gameObject);
        }
    }
}