简体   繁体   中英

Limit the array size 2D (C# UNITY)

Hello guys is it possible to limit the array size just like this example

在此处输入图片说明

Now i want only to show 6 of them.

What i have done so far is this

CustomClass

const int MAX = 104;  // = 8 decks * 52 cards / 4cardsoneround
const int Y = 6;

int[,] arrayRoad = new int[Y, X];

 public int[,] GetRoad(int x) {
    arrayRoad = new int[x, 6];
    return arrayRoad;
}

Now I'm displaying it on my MainClass like this

ScoreBoard bsb = new ScoreBoard();

private void Road()
{
    bsb.makeRoad(history); // Road
    int[,] arrayRoad = bsb.GetRoad(6); //<--- sample value 6

    string s = "";
    for (int y = 0; y < arrayRoad.GetLength(0); y++)
    {
        //just 27 for now

        for (int x = 0; x < 28; x++)
        {
            s += string.Format("{0:D2}",arrayRoad[y, x]);
            s += ".";
        }
        s += "\n";
    }
    Debug.Log(s);
}

The problem with this code is that it's giving me an Array out of index

Is this possible??

Updated

public int[,] GetRoad(int x = MAX,int y = Y) {
    arrayRoad = new int[y, x];

    return arrayRoad;
}

Where in my Max = 104 and Y = 6

int[,] arrayRoad = bsb.GetRoad(12,6); //12 rows and 6 in height

    string s = "";
    for (int y = 0; y < arrayRoad.GetLength(0); y++)
    {
        for (int x = 0; x < arrayRoad.GetLength(1); x++)
        {
            s += string.Format("{0:D2}",arrayRoad[y, x]);
            s += ".";
        }
        s += "\n";
    }
    Debug.Log(s);
}

I have all this value earlier before i perform the update code

在此处输入图片说明

Now when i perform the updated code here's what I got

在此处输入图片说明

The expected result must be this

在此处输入图片说明

Inside of that black marker those twelve columns only must be shown because i declared on my

int[,] arrayRoad = bsb.GetRoad(12,6);

Note this:

 public int[,] GetBigEyeRoad(int x) {
    arrayRoad = new int[x, 6]; // <-------------
    return arrayBigEyeRoad;

There you are fixing the length of the second dimension of the array to 6.

    for (int x = 0; x < 28; x++)
    {
        s += string.Format("{0:D2}",arrayBigEyeRoad[y, x]); // <------------

There, you are trying to access indices up to 28 on the second dimension of the array. The Out of Range error comes from that.

What I did here was copy my old array to the new one just like this code below

int[,] arrayBigRoadResult = new int[6, x];
//copy manually the element references inside array
for (int i = 0; i < 6; i++)
{
    for (int j = 0; j < x; j++)
    {
        arrayBigRoadResult[i, j] = arrayBigRoad[i, j];
    }
 }
return arrayBigRoadResult;

then by calling it just like this

int[,] arrayRoad = bsb.GetRoad(12);

It would only display 12 columns and 6 rows :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM