Raycast2D help...

I’m trying to raycast downwards from my character and I can’t work it out :frowning: I’ve tried lots of things but still have no idea what is making it not work, I’ve tried raycasting against all layers and using a tag instead and even tried just copying the Unity example but its broken (I think, I have no idea what its meant to do)

In the Unity example they check:

if (hit != null)

But that code will always return true, even if its not hitting anything(In the editor it even says this). So the object just fly’s off. So, I guessed that maybe it was just an error and it should be:

if(hit.transform != null)

But that doesn’t work ether…

Here’s my code:

using UnityEngine;
using System.Collections;

public class HeadJump : MonoBehaviour {

	public Transform[] raycastTransforms;
	private int layer;

	void Start(){
		layer = LayerMask.NameToLayer("Enemy");
		Debug.Log("" + layer);
	}
	void Update () {
		foreach(Transform rayTransform in raycastTransforms){
		 RaycastHit2D hit = Physics2D.Raycast(rayTransform.position,-Vector2.up,Mathf.Infinity,layer);
		 if(hit.transform != null){
			Debug.Log("Hello" + hit.transform.name);
		 }
		}
	}
}

Why did Unity change the syntax for raycast 2D :(… I have no idea…

(raycastTransforms consists of two transforms)

The problem for me was, that i was hitting the same gameobject which called the raycast.
To make your layerMask work i think you need to bitshift with ‘layer’ like:

RaycastHit2D hit = Physics2D.Raycast(rayTransform.position,-Vector2.up,Mathf.Infinity,1 << layer);