- Home /
how to destroy game objects with a raycast and health?
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!
Try this:
if (hit.collider.tag == "Enemy")
{
hit.transform.GetComponent<EnemyHealth>().LowerHealth();
}
$$anonymous$$ake sure your enemy object has collision component and EnemyHealth script.
Thanks! Works like a charm. You can use the same as answer, so I can vote it as answer
Answer by nbg_yalta · Feb 07, 2014 at 10:13 AM
You can use SendMessage for this:
......
if (hit.collider.tag == "Enemy")
{
hit.collider.SendMessage("LowerHealth");
}
Your answer
Follow this Question
Related Questions
[Answered](C#) Help with dealing damage to enemy from Raycast 3 Answers
Most direct way to create OnCursorStay "event" in UI. 1 Answer
Is it possible to allow a raycast to pass through a collider to hit things behind it? 6 Answers
Raycast not detecting anything if MainCamera's X rotation is > 41.5 1 Answer
Follow Nearest Target 1 Answer