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