Raycasting not Working

I’m trying to figure out raycasting but I keep getting this error when I try to get the object’s name:
NullReferenceException: Object reference not set to an instance of an object

Here’s my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Raycast : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
      
    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 1f);

        if(hit.collider.gameObject.name == "Square")
        {
            Debug.Log("hit");
        }
    }
}

Does anybody know what I’m doing wrong? Thanks.

Hi owlangford1, you will need to check for the hit.collider object is not null before you access it.

    void Update()
    {
        RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 1f);
      
        if(hit.collider != null)
        {
           if(hit.collider.gameObject.name == "Square")
           {
               Debug.Log("hit");
           }
        }
    }
1 Like