So , I have a ray thats created evry time i click mouse button , and ray can detect what its hitting , but how do I detect of other objects side if its geting hit by the ray so I can take some health away
using UnityEngine;
using System.Collections;
public class shoot : MonoBehaviour {
Ray ray;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit;
if (Input.GetMouseButtonDown (0)) {
if (Physics.Raycast (transform.position, transform.forward, out hit)) {
Debug.Log (hit.transform.name);
Debug.DrawRay (transform.position, transform.forward, Color.red, 25f);
}
}
}
}
Since you have the object hit saved in the Raycast hit variable, you can use the GetComponent function : Documentation for Get Component and then call a public function on the GameObject.
For example, imagine the script you have on the object you want to hit is named ActorEnemyManager
which have a public function Damage(float amount)
, then you could do the following :
if (Physics.Raycast (transform.position, transform.forward, out hit)) {
Debug.Log (hit.transform.name);
Debug.DrawRay (transform.position, transform.forward, Color.red, 25f);
ActorEnemyManager actorEnemyManager = hit.transform.GetComponent<ActorEnemyManager>();
if (actorEnemyManager != null) // Checking if we found a component
actorEnemyManager.Damage(10.0f);
}
You could use use two classes. One sending the ray and one receiving the ray. When the ray hits the object use GetComponent
to get a class attached to the recieving object and then call a public method to apply damage. Also in your question you said click. If you want to call the function on a click you should use Input.GetMouseButton
and use Input.GetMouseButtonDown
if you want to call it the method whenever the mouse button is being held down.
In the class sending the ray:
public float damage = 100f;
void Update(){
if(Input.GetMouseButton(0))
RayClick();
}
void RayClick (){
RaycastHit hit = new RaycastHit;
if (Physics.Raycast (transform.position, transform.forward, out hit)){
ReceivingClass rc = hit.transform.GetComponent<ReceivingClass>();
if(rc != null)
rc.Damage(damage);
}
}
Then in the class to receive the damage:
public float health = 500f;
public void Damage(float damageReceived){
health -= damageReceived;
if(health <= 0f)
//Die...
}