- Home /
Raycast hits wrong object
Hello,
I have a scene with 3 Objects (all of the same Prefab type): The prefab has a script that checks if the player clicked on the object:
void Update() {
if(Input.GetMouseButtonDown(0)) {
Debug.Log("MouseDown");
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit raycastHit;
if(Physics.Raycast(ray, out raycastHit) && raycastHit.collider.gameObject.tag == "Magnet") {
GameObject go = raycastHit.collider.gameObject;
Debug.Log("Hit object: " + go.name);
...
The problem is: When I click ONCE on ONE object, I get the hit 3 times! This is the output when I click ONCE on one object: How is it possible that I hit all 3 objects (when the ray clearly only intersects the geometry of ONE object)?
Answer by compyler · Apr 25, 2020 at 09:30 AM
Damn, I just found the problem! For all people that run into a similar problem: I hit the SAME object 3 times cause the code was executed 3 times and found the same hit every time.
Guess its not a good idea to have Scripts on objects that are multiple times in the scene?
Your answer
Follow this Question
Related Questions
Simulating Bullet Gravity using Raycasting 1 Answer
Raycast, Calculate Random Direction 1 Answer
Raycast is finding all items/script is finding all items - inventory help 1 Answer
Why do my bullets only destroy themselves sometimes after colliding with the wall? 0 Answers
Raycast hit info not registering on specific gameobject 0 Answers