Hello everyone. I am having trouble destroying a gameobject with health throught a raycast. I can destroy the game object directly after a touch. But I want the gameobject to have health. How can I lower the health from the game object throught a raycast? Here is the code to clarify:
public class RaycastTest : MonoBehaviour {
private Ray ray;
private RaycastHit hit;
private EnemyHealth EnemyHealthScript;
// Use this for initialization
void Start () {
EnemyHealthScript = (EnemyHealth)FindObjectOfType(typeof(EnemyHealth));
}
// Update is called once per frame
void Update () {
if (Input.touchCount > 0)
{
ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.tag == "Enemy")
{
EnemyHealthScript.LowerHealth();
}
The: EnemyHleathScript.LowerHealth() is giving me trouble and giving me a NullReferenceExepction. Here is the enemy health script:
public class EnemyHealth : MonoBehaviour {
public int Health = 100;
// Use this for initialization
void Start()
{
Destroy(this.gameObject, 23);
}
// Update is called once per frame
void Update () {
if(Health <=0){
Destroy(this.gameObject);
}
}
public void LowerHealth()
{
Health -= 50;
}
Cheers and thanks in advance!