I'm making a 2D topDown survival game.Before adding an inventory system i adding an object detector

I want to add an object detector because in most inventory system videos, objects are collected simply by touching them, which seems silly. Therefore, I aim to make objects interactive so that players can collect them by pressing ‘E’ instead.

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

public class DedectResources : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey(KeyCode.E))
        {
            RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 10f);
            RaycastHit2D hit1 = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.down), 10f);
            RaycastHit2D hit2 = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.left), 10f);
            RaycastHit2D hit3 = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.right), 10f);

            if (hit || hit1 || hit2 || hit3)
            {
                Debug.Log("hit:" + hit.collider.name);
                Debug.Log("hit:" + hit1.collider.name);
                Debug.Log("hit:" + hit2.collider.name);
                Debug.Log("hit:" + hit3.collider.name);
            }
            else
            {
                Debug.Log("no hit");
            }
        }
    }

 
}

Now, my problem is that I’ve created this raycast code, but there’s an issue. When the raycast detects something within range, it gives a null error and only works when the player is in the middle of the object

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

Hello ThePlayer5133,

in your code you display:

            if (hit || hit1 || hit2 || hit3)
            {
                Debug.Log("hit:" + hit.collider.name);
                Debug.Log("hit:" + hit1.collider.name);
                Debug.Log("hit:" + hit2.collider.name);
                Debug.Log("hit:" + hit3.collider.name);
            }

But what if only one raycast touched an object? so all the other hit variables will be null, but you are trying to access the variable “collider” of something null

1 Like