Block not changing to next sprite

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);
    }

}

Hi Bembrooks,

Have you already compared your code to the Lecture Project Changes which can be found in the Resources of this lecture?

If so, check the Inspector of your block game object. There should be sprites assigned to the hitSprites array of the Block component.

Good call! I forgot that was a resource we had, and I figured out the problem. I wasn’t calling ShowNextHitSprite in HandleHit. Thanks for the help!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms