NullReferenceException: Object reference not set to an instance of an object

Hello,

I have completed this section and I cannot run my game. I noticed the field breakableBlocks is not serialized in Inspector and I do not know why. I have this bug in console upon starting my game:

NullReferenceException: Object reference not set to an instance of an object
Block.Start () (at Assets/Scripts/Block.cs:15)

Here is my Block script:

public class Block : MonoBehaviour
{    
    [SerializeField] AudioClip destroySound;
    
    //cached ref
    Level level;

    private void Start()
    {
        level = FindObjectOfType<Level>();
        level.CountBreakableBlocks();
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        AudioSource.PlayClipAtPoint(destroySound, Camera.main.transform.position);
        Destroy(gameObject);
    }
}

Here is my Level script:

public class Level : MonoBehaviour
{
    [SerializeField] int breakableBlocks;

    public void CountBreakableBlocks()
    {
        breakableBlocks++;
    }

}

Here is Inspector view:

bug_1

Cannot find the solution. Anyone could help?

Regards,
Paweł

Hi Paweł,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.

There seems to be an issue with the level script in your last screenshot. Does the file name match the class name inside the file? For example, is the Level class inside the Level.cs file? The correct spelling is crucial.

Hi Nina,

Got it, thanks!
I called my script “level” (lower case), while in the course it has been called “Level” (capital letter).
So I changed all three instances of the class from “Level” to “level” and it works now. Thank you!

Regards,
Paweł

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms