当我点击 E 时,光线投射没有击中对象,我收到此错误 message:NullReferenceException:Object reference not set to an instance of an object

When I hit E,and the raycast doesnt hit an object,I get this error message:NullReferenceException:Object reference not set to an instance of an object

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

public class Player : MonoBehaviour
{
    [SerializeField] private DialogueUI dialogueUI;

    public Vector3 raypositionup = new Vector3(5, 0, 0);
    public Vector3 raypositiondown = new Vector3(5, 0, 0);

    private float MoveSpeed = 7f;

    public Animator animator;

    public DialogueUI DialogueUI => dialogueUI;

    public Interactable Interactable { get; set; }

    bool move = false;
    bool movefoward = false;

    public Rigidbody2D rb;

    Vector2 movement;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {

        if (DialogueUI.IsOpen) return;

        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");

        if (Input.GetKeyDown(KeyCode.W))
        {
            move = true;
            movefoward = false;
            animator.SetBool("Lookingfoward", true);
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            movefoward = true;
            move = false;
            animator.SetBool("Lookingfoward", false);
        }

        if (Input.GetKey(KeyCode.LeftShift))
        {
            MoveSpeed = 10f;
        }
        else
        {
            MoveSpeed = 7f;
        }

        if (Input.GetKeyDown(KeyCode.Return))
        {
            if (Interactable != null)
            {
                Interactable.Interact(this);
            }
        }

        if (move == true)
        {
            if (Input.GetKey(KeyCode.E))
            {

                Debug.DrawRay(transform.position + raypositionup, transform.up * 2f, Color.red);

                RaycastHit2D hit = Physics2D.Raycast(transform.position + raypositionup , transform.up, 2f);

                if (hit.collider.CompareTag("Object"))
                {
                    Debug.Log("Poop");
                    hit.transform.GetComponent<SpriteRenderer>().color = Color.red;
                }
                if (hit.collider == null)
                {
                    return;
                }
            }
        }

    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * MoveSpeed * Time.fixedDeltaTime);
    }
}

我尝试了几种不同的修复方法,none 似乎有效,例如另一个 if 语句、else 语句,甚至重新设计了整个光线投射系统。如果有人知道一个很好的解决方案。此外,对我的代码的任何批评都是可以接受的,我是编码新手,希望有机会尽可能地清理我的代码。

如果 collider 为 null,您有 return 的代码,但如果比较为 null,则不会捕获:

if (hit.collider == null)
{
 return;
}
elseif (hit.collider.CompareTag("Object")) //No catched if null
{
 Debug.Log("Poop");
 hit.transform.GetComponent<SpriteRenderer>().color = Color.red;
}