Do Something When a Object is hit by a raycast
So i simply want to run some code when my character's Gun Raycast hits a object. That is all i want to do. But nothing is working for me. It would be great if someone helped :).
Are you trying to get it to do something through a script on the object that is hit, or through the object shooting the ray? As far as I know, the best method is through the object shooting the ray. Either way, can you post the script of some things you've tried?
Answer by hopper · Mar 14, 2017 at 04:11 AM
Try this:
float range = 10f;
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out hit, range))
{
if(hit.collider.tag == "Enemy")
{
Debug.Log("Hit!");
}
}
}
Debug.DrawLine(transform.position, transform.forward * range);
}
What this should do is whenever you click the left mouse button, a raycast should fire and hit an object. If it hits an object with a specific tag, it will log to your console "Hit!". You can always remove that if statement if you want to see if an object hits anything at all. Then on your game view, you'll see a button labeled "Gizmos". Click that and now when you fire your gun, you will be able to see your Raycast live in your scene.
Your answer
![](https://koobas.hobune.stream/wayback/20220612113102im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Tennis Ball Hit differents effects and take parabola 0 Answers
Huge Health and Damage Script Problem 0 Answers
How to return a function 0 Answers
I need Function to be in other script 1 Answer
Why is the script not working (function not changing value) 0 Answers