Doubt with using maxHita in HandleHit()

Well another question from my side :-

 private void OnCollisionEnter2D()
    {
        if (tag == "Breakable")
        {
            HandleHits();
        }
    }

    private void HandleHits()
    {
        currentHits++;
        int maxHits = hitSprites.Length + 1;  // ?_?
        if (currentHits >= maxHits)
        {
            DestroyBlock();
            ParticleWhenBlockBreak();
        }
        else
        {
            ShowNextSprite();
        }
    }

In the new maxHits logic, we initialized maxHits variable inside the HandleHits() function which is called whenever the ball collides with a block. But my doubt is whenever the ball will collide with a block maxHit should get some value by hitSprites.Length + 1, but when the ball again collides with the same block, again maxHit should get the same value again n again till infinity as this line int maxHits = hitSprites.Length + 1; will again execute.
But everything’s going right…why??

HitSprites is a fixed array you defined in the inspector one of it’s properties is it’s Length which never changes unless you add or remove elements to the array. So everytime you call that method maxHits works out to the same number everytime, the reason is so you can have as many sprites as you want to increase or decrease the amount of hits it takes to break.

I hope that helps clear things up!

Thnx, now i got it…but one last thing, everytime time the ball collides it calls HandleHits() and again initializes the value of maxHits many times, so rather putting int maxHits = hitSprites.Length + 1; in Start() would be a better option and it will initialize maxHits once…Isn’t it??

In some cases yes but in this instance I would say it’s not worth caching that value when it takes no time at all to calculate.

If it’s quick and easy just calculate, if it’s an expensive operation then cache it.

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