Search code examples
unity-game-engineerror-handlingraycastingray

Unity Raycast2D ScreenPointToRay gives an ERROR


I want to create a simple Ray2D with my mouse Position:

//Create a ray
Ray2D ray = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;

It gives me an error: Ray can't be converted into Ray2D How can I solve this problem?


Solution

  • That's because you are using "ScreenPointToRay" which returns a "Ray" not a "Ray2D".

    Try this:

    RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);