I’m not sure where, but I think I messed up my code somehow. For some reason, the part of it that’s supposed to be loading the next sprite in simply isn’t connecting. I figured this out when it wouldn’t trigger the “block sprite is missing from array” debug message we coded in when hit. I’d really appreciate some help as I can’t figure out what I’ve done wrong. Thanks!
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Block : MonoBehaviour
{
// Configuration parameters
[SerializeField] AudioClip breakSound;
[SerializeField] GameObject blockSparklesVFX;
[SerializeField] int maxHits;
[SerializeField] Sprite[] hitSprites;
//cached reference
Level level;
// State variables
[SerializeField] int timesHit; //todo only serialized for debug purposes
private void Start()
{
CountBlocks();
}
private void CountBlocks()
{
level = FindObjectOfType<Level>();
if (tag == "Breakable")
{
level.CountBlocks();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (tag == "Breakable")
{
HandleHit();
}
else
{
ShowNextHitSprite();
}
}
private void ShowNextHitSprite()
{
int spriteIndex = timesHit - 1;
if (hitSprites[spriteIndex] != null)
{
GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];
}
else
{
Debug.Log("block sprite is missing from array" + gameObject.name);
}
}
private void HandleHit()
{
timesHit++;
if (timesHit >= maxHits)
{
DestroyBlock();
TriggerSparklesVFX();
}
}
private void DestroyBlock()
{
TriggerAudioFX();
Destroy(gameObject);
level.BlockDestoryed();
}
private void TriggerAudioFX()
{
FindObjectOfType<GameSession>().AddToScore();
AudioSource.PlayClipAtPoint(breakSound, Camera.main.transform.position);
}
private void TriggerSparklesVFX()
{
GameObject sparkles = Instantiate(blockSparklesVFX, transform.position, transform.rotation);
Destroy(sparkles, 2f);
}
}