- Home /
Help With RayCasting
Hello,
I have a few objects around my scene, such as a newspaper, a chair and a chocolate bar (tagged correspondently).
What I want to do, is that when the user clicks on either of these objects - it prints to the console the 'tag' or name of the current selected object.
I've been playing around with raycast from camera to mouse position, and I can never get it to work. I have to place a unique script on each of the objects like this:
#pragma strict
function Update(){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; if (collider.Raycast (ray, hit, 100.0) && Input.GetButton("Fire1")) { Debug.DrawLine (ray.origin, hit.point); print("hitting chair"); GameControl.ShelfClicked = true; } }
Can I not just have a 'central control' where it works like this:
If chair has been 'raycast' && Fire1 - print 'touched chair'.
If newspaper has been 'raycast' && Fire1 - print 'touched newspaper'.
and so on ... Instead of placing the raycast script into each object?
Hope that makes sense, Thanks!
Answer by tool55 · Feb 03, 2011 at 12:34 AM
Give this a shot:
if (Physics.Raycast (ray, hit, 100.0) && Input.GetButtonDown("Fire1"))
{
print ("touched " +hit.collider.gameObject.name);
}
Keep all of your variables just as you have them. I haven't tested it, but should be closer to what you want. Oh, and you don't want the script on every object, just one; the camera or the player or whatever.
Your answer
![](https://koobas.hobune.stream/wayback/20220613102526im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Getting a point on ray 1 Answer
default cylinder to indicate hit.normal 1 Answer
Detect Object that are hit by a ray 3 Answers
Need Help with RayCast. No Vector? 1 Answer
Unity | Raycast Hit Empty Object which has Objects as Children 1 Answer