- Home /
Raycast SendMessage not working properly
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");
}
}
}
}
}
Is the "Hit" message being displayed? Also a many similar questions were asked. Here is an example. http://answers.unity3d.com/questions/1158543/sendmessage-not-calling-function-in-other-script.html
Answer by Bunny83 · Jan 04, 2017 at 12:11 PM
not working properly
is not a proper description of your problem. What do you see in your console? How is your enemy structured? Does it have several colliders? Where's the target script located?
Since a lot information is missing we can only guess.
You most likely are "hitting" a child collider but your script is located on a parent. You can use SendMessageUpwards instead. It will do the same as SendMessage but if the message isn't picked up by the object you've hit it will go up the hierarchy and try it again on the parent. It will go all the way up to the top if no object has that method.
Such things are trivial debugging problems that you should be able to figure out yourself. Start by printing the name of the object you have hit. Debug.Log can also receive an additional "context" parameter. When you pass in the object you have hit, you can simply click the debug message in the console and Unity will "ping" / highlight the object in the hierarchy / project panel.
Your answer
![](https://koobas.hobune.stream/wayback/20220612103921im_/https://answers.unity.com/themes/thub/images/avi.jpg)