Index Out Of Range Exception: Array index is out of range (trying to change sprite when hit)

Good morning Developers
i know that this question has been asked before but i didn’t find a solution to my problem in those answers,
first i’d like to tell you that i’m just a beginner in unity :stuck_out_tongue: ,
well here is my problem :
i’m building a brick breaker game
what i’m trying to do is to change the sprite of a brick when it gets hit by the ball,
to do so i’m using this script :

	public int maxHits;
	public int timesHit;
	private LevelManager levelManager;
	public Sprite[] hitSprites;
	
	void Start () {
		timesHit = 0;
		levelManager = GameObject.FindObjectOfType<LevelManager> ();
	}

	void OnCollisionEnter2D(Collision2D collision) {
		print ("collison");
		timesHit++;
	}

        // Update is called once per frame
	void Update () {
		if (timesHit >= maxHits) {
			Destroy (gameObject);
		} else {
			LoadSprite ();
		}
        }

void LoadSprite(){
		int spriteIndex = timesHit - 1;
		this.GetComponent<SpriteRenderer> ().sprite = hitSprites [spriteIndex];
	}
}

but i’m getting this error :
IndexOutOfRangeException: Array index is out of range.
Brick.LoadSprite () (at Assets/Scripts/Brick.cs:34)

and i’m getting it every frame!, so it’s slowing the game scene too much and i can’t test my game anymore!
can you please tell me what did i do wrong and how to fix it??
and it may help if you direct me to a cours to learn more about my error and don’t do it again
thank you have a nice day ^^

timeshit starts at 0.

The loadsprite method is called every frame.

Therefore, the loadsprite method is called when timeshit is still 0.

spriteindex is timeshit -1.

therefore, spriteindex is -1.

You’re trying to get sprite -1.

Add

if(timeshit < 1)
    return;

to the top of your LoadSprite() method.

@A13x231
Thank you for your answer ^^
i added that if condition into LoadSprite() and it worked!! ^^
one other way that i found by my self by mistake lol, is by moving this if condition from update() directly to OnCollisionEnter2D() :

if (timesHit >= maxHits) {
			Destroy (gameObject);
		} else {
			LoadSprite ();
		}

here is the new code :

void OnCollisionEnter2D(Collision2D collision) {
		bool isBreakable = (this.tag == "Breakable")
		if (isBreakable) {
			HandleHits ();
		}
	}

	void HandleHits(){
		print ("collison");
		timesHit++;
		if (timesHit >= maxHits) {
			Destroy (gameObject);
		} else {
			LoadSprite ();
		}
	}

and this solved the problem.
but i admit tho that i don’t know how doing this fixed it, so if you have an explanation i’d appreciate it ^^
thanx again!