- Home /
Getting the object's name from RaycastHit
Hi there, I am trying to get which object I am hitting with my ray. Eventually I want to call a function inside that object's script. as in you fire at a barrel - barrel has a BOOM function in it's script - if the barrel is hit, BOOM gets called.
I think I got the raycasting down:
var ray =Camera.main.ScreenPointToRay(new Vector3(Screen.width/2,Screen.height/2)); var hit : RaycastHit; if (Physics.Raycast (ray, hit, 1000)) {
print(hit.collider); //oh yeah, I am hitting stuff such as, UnityEngine.MeshCollider
Debug.DrawLine (ray.origin, hit.point);//I can also see that the rays work, awesome.
Now I have tried things like hit.BOOM which is of course not working :)
Thanks in advance :)
Answer by duck · Jan 22, 2010 at 04:10 PM
Once you have determined that your raycast actually hit something, you can query your 'hit' object for many different properties.
For the gameObject's name:
hit.collider.gameObject.name;
For the object's tag:
hit.collider.tag
And there are many others - see the RaycastHit manual page.
Because "collider" is a component, you can use "GetComponent" on the hit.collider result, to get access to any other component on the gameObject - including your own script.
You would use something like this (inside your , assuming your script is called "BoomScript" and it has a function in it called "Boom":
if (Physics.Raycast (ray, hit, 1000)) {
var boomScript : BoomScript = hit.collider.GetComponent(BoomScript);
if (boomScript != null) {
boomScript.Boom();
}
}
Thank you sir, this works wonderfully. You have answered in such a way that it made me proud of my question, exactly what I wanted to know. /tips hat
You can also get the name of whatever was hit simply by using "hit.transform.name"
What if you can't use "name" because there's hundreds of them in the level and in the Hierarchy list they have all been assigned different names due to be instances of your prefab? What if you can't use "tag" because, again, there's hundreds of them tagged the same in the level and you only want to affect the single one the raycast has hit rather than some random one the "tag" check in Unity decides to pick at that time? How do you check what specific instance of the object the raycast has actually hit and then affect that one only? In my case I'm shooting a gun and I want to check what it [the raycast] has hit, be it an enemy or a crate or a light or whatever, and then reduce the health of that one specific instance of whatever object it's just shot by a little.