I have literally spent all day researching the light out of Unity C# Raycasting and I have nothing to show for it. I have studied tutorials, online resources, stack overflow questions, and have even word for word copied script in hopes that Unity would finally recognize all my attempts to actually use a Raycast. Here is an example of a script using Raycast that simply won't work for me:
if (mouseDown) {
print ("mouse is down");
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
print ("response???");
}
}
I feel like this should work... but it's not. The mouseDown is working as it should but when I click on my object it refuses to acknowledge the rayhit from my mouse position to the object. I should also mention that the project is in 2D. Any suggestions?
1.If the Object you are trying to detect touch with is an Image
/Canvas
, then this is not how to do this. To detect touch with Image/Canvas, you use have to derive from IPointerDownHandler
or IPointerClickHandler
then implement the functions from them.
public class YourClass : MonoBehaviour,IPointerDownHandler,IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("Clicked");
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Down");
}
}
2.Now if the GameObject you want to detect the touch with is just a 2D Texture or Sprite then use the code below:
if (Input.GetMouseButtonDown(0))
{
Vector2 cubeRay = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D cubeHit = Physics2D.Raycast(cubeRay, Vector2.zero);
if (cubeHit)
{
Debug.Log("We hit " + cubeHit.collider.name);
}
}
For this to work, you must attach Collider2D
to the 2D Texture or Sprite. Make sure that the Collider is covering the 2D Texture or Sprite by re-sizing the collider. Since this is a 2D game, any collider
you are using must end with 2D.For example, there is a Box Collider
and there is a Box Collider 2D
. You must attach Box Collider 2D
. to the Sprite/Texture.
3.If #2 did not work, then your project was created as a 3D instead of 2D. Delete the project, create a new Project and make sure you choose 2D this time. #2 answer should now work as long as a 2D collider
is attached to it.