I came across the SendMessage method and cannot get it to work. I want health to be deducted from the enemy when the raycast hits the enemy. Here’s my code:
EnemyScript
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour {
public int enemyHealth = 10;
void DeductPoints(int damageAmount){
Debug.Log ("Hey!");
enemyHealth -= damageAmount;
}
void Update () {
if (enemyHealth <= 0) {
Destroy (gameObject);
}
}
}
HandGunDamage Script
using UnityEngine;
using System.Collections;
public class HandGunDamage : MonoBehaviour {
public int damageAmount = 5;
public float targetDistance;
public float allowedRange = 15;
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("Fire1")){
RaycastHit hit;
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), out hit)) {
targetDistance = hit.distance;
if(targetDistance < allowedRange){
hit.transform.SendMessage("DeductPoints", damageAmount, SendMessageOptions.DontRequireReceiver);
Debug.Log ("Hit");
}
}
}
}
}