Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从二维网格中的值获取索引_C#_Unity3d - Fatal编程技术网

C# 从二维网格中的值获取索引

C# 从二维网格中的值获取索引,c#,unity3d,C#,Unity3d,我有一个二维数组,类型为Cell,它创建了一个单元网格 private Cell[,] cells; private void Start() { cells = new Cell[mapSize.x, mapSize.y]; } 目前,通过传入匹配的x和y值,我可以从Map访问所有单元格。例如: private Cell GetCell(int x, int y) { return cells[x, y]; } 现在我想通过传入一个cell对象来获得匹配的x和y值 我的解

我有一个二维数组,类型为
Cell
,它创建了一个单元网格

private Cell[,] cells;

private void Start()
{
    cells = new Cell[mapSize.x, mapSize.y];
}
目前,通过传入匹配的x和y值,我可以从
Map
访问所有单元格。例如:

private Cell GetCell(int x, int y)
{
    return cells[x, y];
}
现在我想通过传入一个cell对象来获得匹配的x和y值

我的解决方案是像这样创建
单元
组件

public class Cell : MonoBehaviour
{
    private int x;
    private int y;

    public void InitCell(int indexX, int indexY) // This gets called when intantiating the Cell
    {
        x = indexX;
        y = indexY;
    }
}

但是,我真的必须将这些信息也存储在单元组件中吗?

您不必这样做。 你也可以这样做

foreach(var cell in cells)
{
     if(cell == cellToFind)
     {
          //Gotcha
     }
}

但是将x,y存储在单元格中会更快

您可以使用以下简单功能:

public static Tuple<int, int> CoordinatesOf(Cell[,] cells, Cell value)
{
    int w = cells.GetLength(0); // width
    int h = cells.GetLength(1); // height

    for (int i = 0; i < w; ++i)
    {
        for (int j = 0;j < h; ++j)
        {
            if (cells[i, j] == value)
                 return Tuple.Create(i, j);
        }
    }

     return Tuple.Create(-1, -1);
}
公共静态元组坐标(单元格[,]单元格,单元格值)
{
int w=cells.GetLength(0);//宽度
int h=cells.GetLength(1);//高度
对于(int i=0;i
有点不清楚。是否要搜索单元格以获取x值以及与y中的该值匹配的内容?或者你只想找到x和y的值?我想得到x和y