Raycast2D acting funny

Hi Guys,

I’m trying to understand Raycast2D and I’m following the tutorial, but it’s coming up with an error.

Tutorial example:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    public float floatHeight;
    public float liftForce;
    public float damping;
    void FixedUpdate() {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);
        if (hit != null) {
            float distance = Mathf.Abs(hit.point.y - transform.position.y);
            float heightError = floatHeight - distance;
            float force = liftForce * heightError - rigidbody2D.velocity.y * damping;
            rigidbody2D.AddForce(Vector3.up * force);
        }
    }
}

My try:

	Transform CheckDirection()
	{
		Vector3 fwd = transform.TransformDirection(Vector3.forward);

		RaycastHit2D hit = Physics2D.Raycast(transform.position, fwd,  0.7f, layer);

		if (hit != null)
		{
			if(hit.transform.tag == "Waypoint")
			{
				Debug.Log("YADDA");
				return null;
				//return hit.transform;
			}
			else
			{
				Debug.Log("NUDDA");
				return null;
			}
		}
		else
		{
			Debug.Log("NUDDA");
			return null;
		}
	}

It’s coming up with this error:

NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.CheckDirection () (at Assets/Scripts/PlayerMovement.cs:55)
PlayerMovement.WindowsControls () (at Assets/Scripts/PlayerMovement.cs:154)
PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:38)

…I think it’s telling me that the objects I’m hitting have no transform? But the only objects in that layer have transform… So unless they’re hitting nothing this can’t be hapenning? But in the example it says it will return null if it hits no target.

Can someone explain what’s happenning please?

Docs suck here btw - I already complained but you can file a bug. Basically you shouldn’t use a null check because it’s never actually null. Instead:

  • either use if (hit) // (not a null check, but a bool check)

or

check hit.collider is null.

Mostly, it’s because Physx does return null for hit but Physics2D doesn’t (although this is internally able to return a bool).

Great, thanks for the swift reply :slight_smile: