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();
    }

Works perfectly for me. Are you sure your object you clicked on is named “A”?

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();
	}

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.