Hello! The error that I am currently getting is:
NullReferenceException: Object reference not set to an instance of an object
Block.CountBreakableBlocks () (at Assets/Scripts/Block.cs:23)
Block.Start () (at Assets/Scripts/Block.cs:16)
Here’s the code that I think is relevant to this question:
First, block.cs:
using UnityEngine;
public class Block : MonoBehaviour
{
[SerializeField] private AudioClip breakSound;
[SerializeField] private AudioClip clunkSound;
//Cached reference
private Level level;
private GameSession gamestatus;
[SerializeField] private GameObject particleEffect;
private void Start()
{
CountBreakableBlocks();
gamestatus = FindObjectOfType<GameSession>();
level = FindObjectOfType<Level>();
}
private void CountBreakableBlocks()
{
level.CountBlocksRemaining();
}
private void OnCollisionEnter2D(Collision2D collision)
{
BreakIfBreakable();
}
private void TriggerParticleEffect()
{
GameObject particles = Instantiate(particleEffect, transform.position, transform.rotation);
Destroy(particles, 2f);
}
private void BreakIfBreakable()
{
if (CompareTag("Breakable"))
{
AudioSource.PlayClipAtPoint(breakSound, Camera.main.transform.position); //Play audio SFX
Destroy(gameObject);
TriggerParticleEffect();
level.BlockDestroyed();
gamestatus.AddPoints();
}
else
{
AudioSource.PlayClipAtPoint(clunkSound, Camera.main.transform.position);
}
}
level.cs:
using System;
using UnityEngine;
public class Level : MonoBehaviour
{
[SerializeField] int blocksRemaining = 0; //Serialized for debugging
//Cached reference
SceneLoader sceneLoader;
private void Start()
{
sceneLoader = FindObjectOfType<SceneLoader>();
}
public void CountBlocksRemaining()
{
blocksRemaining++;
}
}
Here’s some more information about the project if it’s relevant at all:
It’s a block breaker game, similar to Atari Breakout
I’m using the “Complete C# Unity Developer 2D: Learn to Code Making Games” course made by GameDev.tv
Thanks in advance for your help!