I edited the Hierarchy just as shown on the video, errors are still there, why?

After following the Lecture 66, Section 5, and correcting the error made by the lecturer by deleting the SceneLoader from the Hierarchy, the errors disappear for him but still persist on my Console. What could be the reason?

Hi Svetlin,

Could you perhaps post your code from Block.cs.


See also;

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

public class Block : MonoBehaviour
{
    [SerializeField] AudioClip breakSound;

    // cached reference
    Level level;

    private void Start()
    {
        level = FindObjectOfType<Level>();
        level.CountBreakableBlocks();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        DestroyBlock();
    }

    private void DestroyBlock()
    {
        AudioSource.PlayClipAtPoint(breakSound, Camera.main.transform.position);
        Destroy(gameObject, 0.1f);
        level.BlockDestroyed();
    }
}
1 Like

Hi Svetlin,

Your error message points to line 15 in your Block.cs script, line 15 is this;

level.CountBreakableBlocks();

Your NullReferenceException error is being thrown because level is null and you are trying access a member of Level, in this case your call to CountBreakableBlocks.

If you look further up at where you initialise this variable you’ll see it’s on line 14, this code;

level = FindObjectOfType<Level>();

What this tells us is that the FindObjectOfType method call did not return a reference to an object of type Level, if it can’t find it, it’s because it isn’t in your scene, or, it is, but it isn’t active (e.g. it’s disabled).

So, do you have a GameObject in your scene with the Level.cs script component attached to it? I’m going to assume not, in which case, add one and this error should go away.

Also - please remember to apply the code fencing when copy/pasting your code, I did provide you with a link above as to how to do this but it doesn’t look like you’ve referred to it.

Hope this helps :slight_smile:

Privacy & Terms