Hmm! I dug threw some of my completed project… still new at this so forgive that it’s taking a little longer. Our level manager / scene manager files are similar. I also struggled to get it working, so here’s my whole Brick file for comparison (some things are slightly different):
Some things to check:
- I ended up using “using UnityEngine.SceneManagement;” at the very top AND “sceneLoader = GameObject.FindObjectOfType();” under Start()… that was able to get it working for me.
- Make sure you have the Level Manager game object on each scene. (Empty Game Object + Level Manager component).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Brick : MonoBehaviour {
public AudioClip crack; //For audio
public Sprite[] hitSprites;
public static int breakableCount = 0;
public GameObject smoke;
private int timesHit;
private SceneLoader sceneLoader;
private bool isBreakable;
// Use this for initialization
void Start () {
isBreakable = (this.tag == "Breakable");
if (isBreakable)
{
breakableCount++;
Debug.Log(breakableCount);
}
sceneLoader = GameObject.FindObjectOfType<SceneLoader>();
timesHit = 0;
}
void OnCollisionEnter2D(Collision2D collision)
{
AudioSource.PlayClipAtPoint(crack, transform.position); //For audio
bool isBreakable = (this.tag == "Breakable");
if (isBreakable)
{
HandleHits();
}
}
void HandleHits ()
{
timesHit++;
int maxHits = hitSprites.Length + 1;
if (timesHit >= maxHits)
{
breakableCount--;
Debug.Log(breakableCount);
sceneLoader.BrickDestroyed();
PuffSmoke(); //For animation
Destroy(gameObject);
}
else
{
LoadSprites();
}
}
void PuffSmoke ()
{
GameObject smokePuff = Instantiate(smoke, transform.position, Quaternion.identity) as GameObject; // This makes an instance of Smoke where bricks are destroyed
ParticleSystem smokePuffPS = smokePuff.GetComponent<ParticleSystem>();
var smokeMain = smokePuffPS.main;
smokeMain.startColor = gameObject.GetComponent<SpriteRenderer>().color;
}
void LoadSprites ()
{
int spriteIndex = timesHit - 1;
if (hitSprites[spriteIndex])
{
this.GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];
}
else
{
Debug.Log("Brick Sprite Missing");
}
}
}