- Home /
Raycast2D doesn't detect objects
Hi! I've got a gameObject and a script attached to it:
void Update ()
{
Collider2D hitObject = Physics2D.Raycast(transform.position, transform.forward).collider;
if(hitObject.gameObject.name == "Enemy")
{
Debug.Log ("enemy killed");
}
}
When I play game, there are lot of enemies around my object, but the script doesn't detect any. Can You tell me why?
Comment
Best Answer
Answer by kkirkfield · Mar 21, 2015 at 09:55 PM
See Physics2D.Raycast() for an example. First off, you need to check that the hit is not null before trying to access the collider. If it doesn't hit anything, it will cause an error. Then make sure the object that you are trying to raycast are on the layer being used for raycasting. If that still doesn't work, then it could be your vectors if you are getting them from Vector3s. Make sure the vectors are converted to Vector2s correctly.