- Home /
Raycast2D not returning any transform instead keeps returning void.
public class Raycasting : MonoBehaviour
{
Vector2 mousePosition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
if (Input.GetMouseButtonDown(0))
{
mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Debug.Log("Raycast");
RaycastHit2D hit = Physics2D.Raycast(mousePosition, transform.forward, 100.0f);
Debug.DrawRay(mousePosition, this.gameObject.transform.TransformDirection(Vector3.forward), Color.green);
Debug.Log(hit);
Debug.Log(hit.transform);
if (hit.transform != null)
{
Debug.Log(hit.transform.gameObject);
}
}
}
}
I'm not getting any errors, but the hit.transform keeps giving null. the targeted gameObject has a collider and evrything.
Answer by Zelacks · May 18, 2021 at 09:01 AM
You need to give more information about what you are trying to achieve. When hit.transform is null, it means you are not hitting anything. I am going to assume you are trying to make it so you get the transform of whatever you click on (I could be completely wrong but I am just guessing due to a lack of information).
The main problem is that you need to transform the mouse click to a world position, since Input.mousePosition is not a world position but rather a position on the screen.
var clickPosition = (Vector2)(Camera.main.ScreenToWorldPoint( Input.mousePosition ));
This should change it so you get a world position, based on the position of your main camera and where the user clicked.
Also modifying the draw ray, to have a duration (without the duration the ray immediately disappears and wont be visible) and a direction to the right (it doesnt represent the ray we are making but its close enough to atleast debug where the ray is being directed).
Debug.DrawRay(clickPosition, Vector2.right, Color.green, 5f);
To finish off, we just need to use our click Position, and a direction of zero (meaning directly on the point) to get what is under the cursor
RaycastHit2D hit = Physics2D.Raycast(clickPosition, Vector2.zero);
Full code:
using UnityEngine;
public class Raycasting : MonoBehaviour
{
Vector2 mousePosition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
mousePosition = Input.mousePosition;
if (Input.GetMouseButtonDown(0))
{
var clickPosition = (Vector2)(Camera.main.ScreenToWorldPoint( Input.mousePosition ));
RaycastHit2D hit = Physics2D.Raycast(clickPosition, Vector2.zero);
Debug.DrawRay(clickPosition, Vector2.right, Color.green, 5f);
Debug.Log(hit);
Debug.Log(hit.transform);
if (hit.transform != null)
{
Debug.Log(hit.transform.gameObject);
}
}
}
}