Hello,
So I am currently working on a survival game and I am making a script to deduct health with damage.
However, the health stays the same?
using UnityEngine;
using System.Collections;
public class MeleeSystem : MonoBehaviour {
public int Damage = 50;
public float Distance;
public float MaxDistance = 1.5f;
void Update () {
if (Input.GetButtonDown (“Fire1”)) {//default fire button
RaycastHit hit;
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), out hit)) {
Distance = hit.distance;
if (Distance < MaxDistance) {
hit.transform.SendMessage (“ApplyDamage”, Damage, SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
using UnityEngine;
using System.Collections;
public class EnemyLogic : MonoBehaviour {
public int Health = 100;
private void ApplyDamage (int Damage){
Health -= Damage;
if (Health <= 0) {
Dead();
}
}
private void Dead(){
Destroy (this.gameObject);
}
}
What is wrong and why won't the health deduct?
Thanks!
Start with this: Put Debug.Log("Applying Damage: "+Damage); into your ApplyDamage function. This will let you know whether the function is being called or not.
Second: Use code tags to make your code more readable.
Third: I’m pretty sure your problem is that ApplyDamage is private. Make it public.
Thanks for the quick reply.
I just checked and the raycast is indeed being cast and distance is being calculated.
using UnityEngine;
using System.Collections;
public class EnemyLogic : MonoBehaviour {
public int Health = 100;
public void ApplyDamage (int Damage){
Debug.Log ("Applying Damage: " + Damage);
Health -= Damage;
if (Health <= 0) {
Dead();
}
}
private void Dead(){
Destroy (this.gameObject);
}
}
So that means that, whatever object is being hit, does not have that script on it. Try outputting hit.gameObject.name - it’s possible your raycast is running into an unexpected collider, or maybe it’s hitting a collider that’s a child of the Enemy (but not the Enemy itself).
Well here’s what my enemy looks like? What needs the collider on it? https://imgur.com/V9Oe7D8
Rigth now i have a box collider on pcube11
Got it thanks