SystemicPlural
SystemicPlural

Reputation: 5789

Convert this multidimensional array definition in c# line to UnityScript for Unity

I'm following this unity tutorial, but converting the script to UnityScript as I go.

Mostly it has been fine, but this line is throwing me.

Color[][] tiles = new Color[numTilesPerRow*numRows][];

I believe I should be doing something like this, but it isn't working.

var tiles = new Color[numTilesPerRow*numRows][];

I get an error:

';' expected. Insert a semicolon at the end.

Edit:

Here is the function I am converting in full:

Color[][] function ChopUpTiles() {
    int numTilesPerRow = terrainTiles.width / tileResolution;
    int numRows = terrainTiles.height / tileResolution;

    Color[][] tiles = new Color[numTilesPerRow*numRows][];

    for (int y=0; y<numRows; y++) {
        for (int x=0; x<numTilesPerRow; x++) {
            tiles[y*numTilesPerRow + x] = terrainTiles.GetPixels(x*tileResolution, y*tileResolution, tileResolution, tileResolution);
        }
    }

    return tiles;
}

Edit 2:

I have worked out how to get it to work, but I get a downcast warning:

var tiles = new Array();

Does the job, but the problem is that I don't know to imply that this is an array of color arrays I get a downcast warning.

Upvotes: 1

Views: 681

Answers (2)

SystemicPlural
SystemicPlural

Reputation: 5789

I managed to prevent the downcast warning by assigning the color array to a variable first. No idea why this is acceptable when direct assignment isn't.

function ChopUpTiles() {
    var numTilesPerRow = terrainTiles.width / tileResolution;
    var numRows = terrainTiles.height / tileResolution;

    var tiles = new Array();

    for(var y : int = 0; y < numRows; y++) {
        for(var x : int = 0; x < numTilesPerRow; x++) {
            var tileColors = terrainTiles.GetPixels(
                x*tileResolution, 
                y*tileResolution, 
                tileResolution, 
                tileResolution
            );
            tiles[y*numTilesPerRow + x] = tileColors;
        }
    }
    return tiles;
}

Upvotes: 0

Luaan
Luaan

Reputation: 63732

Jagged arrays don't work like this in Javascript.

Have a look at this solution: http://answers.unity3d.com/questions/54695/how-to-declare-and-initialize-multidimensional-arr.html

Basically, get an array, and then initialize each of the indices to a new array.

Of course, if it's statically initialized, you can use something like this:

[[1, 3, 4], [1, 5, 5], ... ]

Is there a reason why you're using a jagged array rather than a simple multi-dimensional array?

Upvotes: 1

Related Questions