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]
Hi, please edit the title of this post so users can see what you are asking for specifically. Also, please write where you think the problem lies and what you've attempted to do to try and fix it.
– SaraCeciliaHi, using Debug.Log("some text telling where you are in the execution of the code"); you can check what condition was true or false: it will help you narrow the problem and find why/where it doesn't work. Debug.DrawLine or .DrawRay is also very useful to display rays or vectors and see if everything is where is should be.
– _dns