- Home /
Enemy's health wont get set from different script.
I'm trying to access the health variable from an EnemyMovement class and apply damage/subtract from that health through a different class.
using UnityEngine;
using System.Collections;
public class hitMarker
: MonoBehaviour {
public EnemyMovement enemyMovement;
int enemyHealth;
void Start(){
enemyHealth = enemyMovement.health;
}
void OnCollisionEnter2D(Collision2D collision){
if (collision.gameObject.tag == "enemy") {
//Debug.Log ("hit");
enemyHealth -= DonnyMovement.damageKick;
enemyMovement.health = enemyHealth;
}
}
}
I believe my problem is the health variable isn't getting set to the new damage version of it.
You don't clearly explain what is going on and what is expected. It may be an script order issue, especially if you initialize the value of enemy$$anonymous$$ovement.health in the Start() of that script. But regardless, why use 'enemyHealth' at all? Why not just do:
enemy$$anonymous$$ovement.health -= Donny$$anonymous$$ovement.damage$$anonymous$$ick;
If I do that, I get the error
Object reference not set to an instance of an object
What is going on is the enemy isn't losing any health. What is expected is for it to lose health.
Answer by smallbit · Jul 18, 2014 at 06:24 AM
Looks like your variable enemyMovement is not assigned. What line give you that error?
If the enemyMovement script is on enemy GameObject you should do like this
if (collision.gameObject.tag == "enemy") {
enemyMovement = collision.gameObejct.GetComponent<EnemyMovement>();
//Debug.Log ("hit");
enemyMovement.health -= DonnyMovement.damageKick;
Otherwise it makes no sense !