- Home /
Get Component in RaycastHit game object
Im making a game in which the player (a sphere) shoots laser beams via Raycast at enemies (cubes). I want to find the "EnemyHealth.cs" component in the object that it hits and if it has the component, to trigger a bool named "isHit"
Here is my code...
EnemyHealth.cs
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour
{
public int health;
public bool isHit;
void Update ()
{
if(isHit)
{
health--;
}
if(health <= 0)
{
Destroy(gameObject);
}
}
}
Attack.cs
using UnityEngine;
using System.Collections;
public class Attack : MonoBehaviour
{
public float range = 0f;
private GameObject enemyTargeted;
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
RaycastHit hit;
Ray ray = new Ray(transform.position, Input.mousePosition);
if(Physics.Raycast(ray, out hit, range))
{
if(hit.collider.tag == "Enemy")
{
hit.gameObject.GetComponent<EnemyHealth>().isHit = true;
}
}
}
}
}
Thanks!
Thanks, but I still can't figure out how to turn isHit back to false after its hit. Any suggestions?
Doing it as @767_2 says you don't have any need for the variable isHit nor for its if in the Update method.
If you still want to do it as you were doing it, you can set isHit to false at the end of the Update.
Answer by 767_2 · Sep 20, 2014 at 11:02 AM
it is better to do this
if(hit.collider.tag == "Enemy")
{
hit.gameObject.GetComponent<EnemyHealth>.health--;
}
Your answer
Follow this Question
Related Questions
C# raycast shooting script broken 1 Answer
Having a RaycastHit event create a component? 1 Answer
Trouble with checking Raycast 1 Answer