0

I was following a unity tutorial and the guy was making interactable objects like chests, NPCs, etc. He was making it so that when you touch an interactable object you would get a message in your console but it doesn't wanna work and I don't know why.

Here is the error message:

NullReferenceException: Object reference not set to an instance of an object Collidable.OnCollide (UnityEngine.Collider2D coll) (at Assets/Scripts/Collidable.cs:34) Collidable.Update () (at Assets/Scripts/Collidable.cs:25)

Here is my code:

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

public class Collidable : MonoBehaviour
{
    public ContactFilter2D filter;
    private BoxCollider2D boxCollider;
    private Collider2D[] hits = new Collider2D[10];

    protected virtual void Start()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    protected virtual void Update()
    {
        // Collision Work
        boxCollider.OverlapCollider(filter, hits);
        for (int i = 0; i < hits.Length; i++)
        {
            if (hits[i] = null)
                continue;

            OnCollide(hits[i]);

            // The array is not cleaned up, so we have to clean it up ourself
            hits[i] = null;
        }
    }

    protected virtual void OnCollide(Collider2D coll)
    {
        Debug.Log(coll.name);
    }
}

Thanks in advance.

  • Something is `null`. Find what's null, make it not null. Perhaps `boxCollider` is `null`? – ProgrammingLlama Aug 16 '21 at 09:40
  • Look at the line above `OnCollide` - you are checking to see if `hits[i] = null`. `=` is not a comparison operator - it's the assignment operator. Your `null` check is actually setting `hits[i]` to `null` just before you call `OnCollide`. Change it to `==`. – Charleh Aug 16 '21 at 09:43

0 Answers0