user3915050
user3915050

Reputation:

How to access the 2D array in my custom class directly

I have class ShapeMap which contains 2D int array shapeMap. in my main script I reference my class as ShapeMap map is there a way I can get value using int value = map[x,y]?

My ShapeMap class is

using UnityEngine;
using System.Collections;
using System;

public class ShapeMap {

private int[,] shapeMap;

public ShapeMap(int width, int height, string seed, int randomFillPercent, int smoothAmount) {

    shapeMap = new int[width, height];

    RandomFillMap (randomFillPercent, seed);

    for (int i = 0; i < smoothAmount; i++) {

        Smooth ();

    }

}

private void RandomFillMap() {

}

private void Smooth() {

}

}

and my Main Script is

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

public class MapGenerator : MonoBehaviour {

ShapeMap map;

public int width, height, fillPercent, smoothAmount;
public string seed;
public bool useRandomSeed;

private void Awake() {

    if (useRandomSeed) {

        seed = Time.time.ToString ();

    }

    map = new ShapeMap (width, height, seed, fillPercent, smoothAmount);

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            int value = map [x, y];

            if (value == 1) {

                // Do This

            } else {

                // Do That

            }

        }

    }

}
}

Upvotes: 0

Views: 118

Answers (1)

mrogal.ski
mrogal.ski

Reputation: 5920

All you have to do is to modify your ShapeMap adding indexer:

public int this[int x, int y]
{
    get { return shapeMap[x, y]; }
    set { shapeMap[x, y] = value; }
}

Try this online


More information about indexers you can find here

Upvotes: 3

Related Questions