I’m working on a basic HP script (copying the one found in this video - Unity 3d: Simple First-Person Shooter Tutorial - Part 7 - YouTube - just with some modified names). However, when I’m in game the object I shoot isn’t being destroyed once it’s taken ‘lethal’ damage.
Here is the HasHealth.cs
snippet:
using UnityEngine;
using System.Collections;
public class HasHealth : MonoBehaviour {
public float objectHitPoints = 100f;
public void receiveDamage (float damageAmount) {
// Decrement the HP each time damage is taken
objectHitPoints -= damageAmount;
// When the object has no more HP...
if (objectHitPoints <= 0) {
Die();
}
}
void Die (){
Destroy (gameObject);
}
}
and here is the excerpt from my Player_Shoots.cs
file.
using UnityEngine;
using System.Collections;
public class Player_Shoots : MonoBehaviour {
public float damage = 50f;
public GameObject bulletPrefab;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0) && clipSize > 0) {
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
RaycastHit hitInfo;
// Raycast to detect hits
if(Physics.Raycast(ray, out hitInfo)){
Vector3 hitPoint = hitInfo.point;
// Deal damage to target, IF it has health
HasHealth h = gameObject.GetComponent<HasHealth>();
if (h != null) {
h.receiveDamage(damage);
}
// Instantiate our bullet at the hitPoint
if(bulletPrefab != null){
GameObject bullet = (GameObject)Instantiate(bulletPrefab, hitPoint, Camera.main.transform.rotation);
bullet.rigidbody.AddForce(0, 400 , 0);
}
}
}
}
}
I’ve also attached a screenshot of the Inspector panel of my target cube - the object that should be destroyed once shot twice.
[33664-screen+shot+2014-10-14+at+11.23.18.png|33664]