Hi everybody,
I’m struggling a bit with the BlockBreaker project.
Whenever I test the game the hit counter goes up when a block is hit and i have set a maxhit (the sprite also cylces) but the block never actually gets deleted. The counter just goes on and on.
The destroy method has worked before but I’ve got the feeling I might have missed something really small.
Thanks in advance for any help
code :
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 serialized for debug
private void Start()
{
CountBreakableBlocks();
}
private void CountBreakableBlocks()
{
level = FindObjectOfType<Level>();
if (tag == "Breakable")
{
level.CountBlocks();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (tag == "Breakable")
{
HandleHit();
}
}
private void HandleHit()
{
timesHit++;
int maxHits = hitSprites.Length + 1;
if (timesHit >= maxHits)
{
DestroyBlock();
}
else
{
ShowNextHitSprite();
}
}
private void ShowNextHitSprite()
{
int spriteIndex = timesHit - 1;
if(hitSprites[spriteIndex] != null)
{
GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];
}
else
{
Debug.LogError("Block sprite is missing from array" + gameObject.name);
}
}
private void DestroyBlock()
{
PlayBlockDestroySFX();
Destroy(gameObject);
level.BlockDestroyed();
TriggerSparklesVFX();
}
private void PlayBlockDestroySFX()
{
FindObjectOfType<GameSession>().AddToScore();
AudioSource.PlayClipAtPoint(breakSound, Camera.main.transform.position);
}
private void TriggerSparklesVFX()
{
GameObject sparkles = Instantiate(blockSparklesVFX, transform.position, transform.rotation);
Destroy(sparkles,1f);
}
}