- Home /
Raycast hitting more than once
I've just noticed now that my raycast is behaving strangely, when I click on an object I want my ray to get the information of that object and behave accordingly, as of now it seems to multiply that ray each time I click on my objects.
Screenshot when i first click an object:
and heres the second time I click an object:
It has now output as if i've hit the second object twice, and this goes up by one each time i've clicked on a new object. Does anyone know why this is?
Here is my code:
using UnityEngine;
using System.Collections;
public class selectObject : MonoBehaviour
{
public bool isSelected = false;
public string ballColor = "";
public GameObject selectedBall;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
playNextLevel ();
if (Input.GetMouseButtonDown (0))
{
RaycastHit hitInfo = new RaycastHit ();
bool hit = Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (Input.GetMouseButtonDown (0) && hit)
{
Debug.Log("Hit " + hitInfo.transform.gameObject.name);
if (hitInfo.transform.gameObject.tag == "redBall")
{
isSelected = true;
ballColor = "red";
selectedBall = hitInfo.transform.gameObject;
}
else if(hitInfo.transform.gameObject.tag == "blueBall")
{
isSelected = true;
ballColor = "blue";
selectedBall = hitInfo.transform.gameObject;
}
else if(hitInfo.transform.gameObject.tag == "greenBall")
{
isSelected = true;
ballColor = "green";
selectedBall = hitInfo.transform.gameObject;
}
else if(hitInfo.transform.gameObject.tag == "yellowBall")
{
isSelected = true;
ballColor = "yellow";
selectedBall = hitInfo.transform.gameObject;
}
}
}
}
}
Any chance you are instantiating an object that has the script above on it? While running and outputting too many log statements, enter the 'selectObject' in the search field in the upper right corner of the Hierarchy window to make sure this script is only on one object.
$$anonymous$$inor nit. You don't have to check On$$anonymous$$ouseDown() again on line 29...just check 'hit'.
That was it exactly @robertu . I had this script on each of my objects, i've taken it off them and placed it on my camera ins$$anonymous$$d which produces the same effect without the result above, thank you
Your answer
![](https://koobas.hobune.stream/wayback/20220613155423im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2.5D Shooting Rigidbodies vs RayCasts 0 Answers
Most direct way to create OnCursorStay "event" in UI. 1 Answer
Is it possible to allow a raycast to pass through a collider to hit things behind it? 6 Answers
Raycast not detecting anything if MainCamera's X rotation is > 41.5 1 Answer
Follow Nearest Target 1 Answer