Decreasing the health of target

Hi, i’ve been trying to figure this out for a while, and i can’t get the code to work the way i want. Could someone help me? :slight_smile:

I have a zombie that of course has a melee attack, and when he attacks me, i want my health to decrease.

I have two scripts, health script and AI script.
It is in the AI script that i want my zombie to attack, and then i want the health script that is attached to the zombies target to decrease (if it makes sence)

this is in the AI script

	//When entering attack range, start attacking
    var range = Vector3.Distance(target.position, transform.position);
    	if (range <= attackRange  deathInhibit == 1  target.health != 0){
    		isAttacking = true;
    		target.healthScript.health -= 20;
    		print ("hit");
    		
    		animation.Play("attack");
	}

so many variables, are you sure in attackRange, deathInhibit variables?.

and what is a target is it gameObject? if yes, you need to use following syntax

target.getComponent<HealthScript>().health -= 20;

or if you use javascript

target.gameObject.GetComponent(HealthScriptName).health -= 20

And last question, do you use colliders ?

I’m pretty sure about everything since all of it works as intended, except the health decrease :stuck_out_tongue:

I don’t use colliders for the attacks no :slight_smile:

I do have another problem with colliders and gravity though, but that’s a totally different matter :slight_smile:

I tried this line

target.gameObject.GetComponent(HealthScriptName).health -= 20

It’s not working, i get this error:

Assets/_Scripts/AI.js(69,47): BCE0023: No appropriate version of ‘UnityEngine.GameObject.GetComponent’ for the argument list ‘(float)’ was found.

sorry i’m not experienced in JS, but you error body indicates that float values come to parameter in GetComponent function, but it must be string or type,

so just try to provide a script name in a quotes

target.gameObject.GetComponent("HealthScriptName").health -= 20

is your health script called “HealthScriptName”? does you health script have a public var of type float for the health or did you use an int?

Thanks, that removed the error. However, i’m now getting a null referance exception when the zombie is trying to attack me. :confused:

NullReferenceException: Object reference not set to an instance of an object
Boo.Lang.Runtime.RuntimeServices.InvokeBinaryOperator (System.String operatorName, System.Object lhs, System.Object rhs)
AI.Update () (at Assets/_Scripts/AI.js:69)

no my health script is called “Health” i wrote that in my code :slight_smile: