- Home /
Question by
NutellaDaddy · Jan 16, 2014 at 04:14 AM ·
c#
Health script not working, why?
I have enemyDamage defined in another script so why wont this work? Help please!
using UnityEngine; using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int playerHealth = 100;
bool dead = false;
void OnColliderHit()
{
if (gamobjectWithTag ("Enemy"))
{
playerHealth - enemyDamage;
}
}
void Update()
{
if (playerHealth <= 0)
dead == true;
if(dead == true)
{
Application.LoadLevel(Application.LoadedLevel);
}
}
}
Comment
I see a couple of problems here.
First, replace the OnColliderHit() function with:
OnCollisionEnter(Collider collider){
if(collider.tag == "Enemy")
playerHealth -= enemyDamage;
}
Second, at link 18 you want dead = true. The == is a comparison, so it won't change the value.
That too! The script that contains the enemyDamage information needs to be referenced here.
Best Answer
Answer by felixpk · Jan 16, 2014 at 02:12 PM
public class PlayerHealth : MonoBehaviour {
public int playerHealth = 100;
bool dead = false;
void OnCollisionEnter(Collider other)
{
if (other.gameObject.tag == "Enemy")
{
enemyDamage = other.getComponentInChildren<EnemyScript>().damage;
playerHealth = playerHealth - enemyDamage;
}
}
void Update()
{
if(playerHealth <= 0){
dead = true;
Application.LoadLevel(Application.LoadedLevel);
}
}
}
Then to all Enemy's you attach a script like
public class EnemyScript : MonoBehavior{
public int damage = 10;
}
Try to analyze the code, there are several mistakes you made, but this way it should work.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130542im_/https://answers.unity.com/themes/thub/images/avi.jpg)