Hello, folks. I’m pretty new to all of this, but I’m trying my best
During the lecture at the point where we first input the following:
private void Awake()
{
int gameStatusCount = FindObjectsOfType<GameStatus>().Length;
if (gameStatusCount > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
…I immediately ran into a bug where instead of seeing the “DontDestroyOnLoad” in the hierarchy I get an error stating _NullReferenceException: Object reference not set to an instance of an object
Block.DestroyBlock () (at Assets/Scripts/Block.cs:25)
Block.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/Block.cs:20)
_
I have gone back through both my Block.cs and my GameStatus.cs and have played with the order of some things but to no avail. Here are the script as they stand:
Block.cs
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() { FindObjectOfType<GameStatus>().AddToScore(); AudioSource.PlayClipAtPoint(breakSound, Camera.main.transform.position); Destroy(gameObject); level.BlockDestroyed(); }
}
GameStatus.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;public class GameStatus : MonoBehaviour {
//config params [Range(0.1f, 3f)] [SerializeField] float gameSpeed = 1f; [SerializeField] int pointsPBD = 10; // PBD = Per Block Destroyed [SerializeField] TextMeshProUGUI scoreText; // state vars [SerializeField] int currentScore = 0; private void Awake() { int gameStatusCount = FindObjectsOfType<GameStatus>().Length; if (gameStatusCount > 1) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); } } private void Start() { scoreText.text = currentScore.ToString(); } // Update is called once per frame void Update () { Time.timeScale = gameSpeed;
}
public void AddToScore() { currentScore = currentScore += pointsPBD; scoreText.text = currentScore.ToString(); }
}
Ultimately what is happening is that once I fire the ball (raindrop) at the block (umbrella) the error appears, and the block is being tied to the “DontDestroyOnLoad” rather than the GameStatus.
Any guidance would be greatly appreciated.
-Cameron