0

im trying to create a matrix and populate it with strings so i can manipulate it later, heres my code

using UnityEngine;
using System.Collections;

public class ScenarioMatrix : MonoBehaviour {

    public GFRectGrid _grid;
    public string[,] _scenarioArray;
    /*
    USAREMOS A SEGUINTE NOMECLATURA PARA O GRID
    E = GRID VAZIO TEM SOMENTE O CENARIO
    SP = Spawn Point, é onde o player começa
    EP = é onde o player termina
    L = Lajota é o caminho onde o player pode andar
    CG = color get, é onde o bloco pega uma cor
    CD = color drop é onde o bloco deixa a cor
    */
    private string[] _values = {"E","SP","EP","L","CG","CD" };

    // Use this for initialization
    void Start() {

        _scenarioArray = new string[(int)_grid.size.x, (int)_grid.size.z];

        //montamos o array
        for (int _largura = 1; _largura <= _grid.size.x; _largura++)
        {
            for (int _comprimento = 1; _comprimento <= _grid.size.z; _comprimento++)
            {
                string _valor = _values[Random.Range(0, _values.Length-1)];
                _scenarioArray[_largura, _comprimento] = _valor;
                //Debug.Log(_values[Random.Range(0, _values.Length)]);
            }

        }
        Debug.Log(_scenarioArray);
    }


    // Update is called once per frame
    void Update () {

    }
}

So far im getting the error IndexOutOfRangeException: Array index is out of range. ScenarioMatrix.Start () (at Assets/Game/Scripts/ScenarioMatrix.cs:30)

what can i be doing wrong in this code?

3
  • 1
    what is your (int)_grid.size.x, (int)_grid.size.z sizes? Commented Mar 21, 2016 at 20:44
  • the site is 5x5 usualy but can change, and should change Commented Mar 21, 2016 at 20:49
  • change for (int _largura = 0; _largura < _grid.size.x; _largura++) and for (int _comprimento = 1; _comprimento < _grid.size.z; _comprimento++) Commented Mar 21, 2016 at 20:55

1 Answer 1

2

replace _comprimento <= _grid.size.z with _comprimento < _grid.size.z

and

_largura <= _grid.size.x with _largura < _grid.size.x

Arrays index are 0 based (They start from 0, not 1)

Sign up to request clarification or add additional context in comments.

3 Comments

worked the error is fixed how can i debug.log this matrix to see it?
just do //Debug.Log(_valor); in the inner for loop, Just after _scenarioArray[_largura, _comprimento] = _valor;
you should also start the loop with index 0. int _largura = 0 and int _comprimento = 0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.