Alan Vieira Rezende
Alan Vieira Rezende

Reputation: 412

Max array range limit

I'm working on code for a 2D game where the player has 3 hearts.

If the player collides with a bombPrefab, he loses 1 heart. If the player collides with a heartPrefab, he wins an extra heart. If he collides 3 consecutive times with a bombPrefab, the game ends.

The Hearts texture is as follows. Array 0 (3 hearts) array 1 (2 hearts) array 2 (1 heart).

I am having a problem limiting the array! I want to know how to get the following response: If the player has 3 hearts and collides with a heartPrefab, only the object is destroyed, there is no change in the number of hearts the player has.

The code below works to take and give extra hearts. But when I collide with one heartPrefab, and I already have 3 hearts (maximum) I get the error: index is out range array.

How should I proceed? C# answer if possible

using UnityEngine;
using System.Collections;
using UnityEngine;
using System.Collections;

public class Heart : MonoBehaviour
{
    public Texture2D[] initialHeart;
    private int heart;
    private int manyHeart;

    void Start ()
    {
        // The game start with 3 hearts at RANGE 0
        GetComponent<GUITexture> ().texture = initialHeart [0];
        heart = initialHeart.Length;
    }

    public bool TakeHearts ()
    {
        if (heart < 0) {
            return false;
        }

        if (manyHeart < (heart - 1)) {
            manyHeart += 1;
            GetComponent<GUITexture> ().texture = initialHeart [manyHeart];
            return true;
        } else {
            return false;
        }   
    }

    public bool AddHearts ()
    {
        if (heart <= 2) {
            return false;
        }

        if (manyHeart < (heart + 1)) {
            manyHeart -= 1;
            GetComponent<GUITexture>().texture = initialHeart [manyHeart];
            return true;
        } else {
            return false;
        }   
    }
}

Upvotes: 1

Views: 527

Answers (1)

MatthewS
MatthewS

Reputation: 61

You are overcomplicating the if statements (unless there is some other reason for doing so)... var manyHeart and heart are always inversely related. Simply use:

public bool AddHearts ()
{
    if (manyHeart > 0) {
        manyHeart -= 1;
        GetComponent<GUITexture> ().texture = initialHeart [manyHeart];
        return true;
    } else {
        return false;
    }   
}

Upvotes: 1

Related Questions