- Home /
Raycast Not Working
Hey all,
I'm trying to make an object (with a box collider) interact with a click to exit out of a while loop using a Raycast. However, although I think I have all the components necessary to initiate it, nothing happens when I click on the object, and the while loop keeps looping. The snippet of code follows:
public IEnumerator Qone()
{
t.text = "A: 1";
while (i == 0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.name == "A")
{
Debug.Log("hit");
i = 1;
}
}
}
Debug.Log("F");
yield return null ;
}
i = 0;
StopAllCoroutines();
}
Your code works for me. Can you post a screenshot of your Hierarchy and Inspector of the object in question?
@Ymrasu Yes, here they are. The object in question is "A." (Don't $$anonymous$$d how unorganized they are)
Answer by YuBen · Feb 08, 2019 at 01:13 AM
I've solved it! For some reason, Box Collider 2D doesn't work with Raycast, so putting a normal Box Collider on the object fixed the problem. Thanks for your help.
Answer by blueshark- · Feb 05, 2019 at 07:29 PM
Works perfectly for me. Are you sure your object you clicked on is named "A"?
Yes, the object is named A. However, this script is attached onto the "A" object; does that make a difference?
Answer by Ymrasu · Feb 05, 2019 at 10:46 PM
Physics.Raycast returns the first thing it hits. If you happen to have anything in front of 'A' or if your B, C, and D all have box colliders as well, they could be the ones getting hit.
Try Physics.RaycastAll:
public IEnumerator Qone()
{
//t.text = "A: 1";
while (i == 0) {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray);
foreach(var hit in hits) {
if (hit.transform.name == "A") {
Debug.Log("hit");
i = 1;
}
}
}
Debug.Log("F");
yield return null;
}
i = 0;
StopAllCoroutines();
}
@Ymrasu Thanks for responding. However, I tried using this method and sadly the result was the same as before. I even tried making another scene using this code and just one object, but it still did not work. Do you think it might be a problem with my editor?
Is this how you want the object to behave? Behaviour GIF
@xBlackhawk Yes, the only difference is that I'm using Unity2d.
Your answer
Follow this Question
Related Questions
Problem with raycast vertical 1 Answer
RayCast2d Not colliding with objects in other layers 1 Answer
Ray is not being detected 0 Answers