索引超出了数组的界限.3d阵列



IndexOutOfRangeException:索引超出了数组的界限。(包装器托管到托管(系统。对象ElementAddr_4(object,int,int(Camera_s。启动(((在Assets/scripts/Camera_s.cs:19(

Script Move.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public Block scr;
public Camera_s cam;
public Transform my_block;
private int[,,] grid;
void Start()
{
my_block = gameObject.transform.parent;
scr = my_block.GetComponent<Block>();
cam = GameObject.Find("Main Camera").GetComponent<Camera_s>();
grid = cam.Grid;
}
void OnMouseDown(){
if (scr.IsActive){
if (gameObject.transform.name == "left"){
my_block.position -= new Vector3(cam.Jump_Size, 0f);
}
else if (gameObject.transform.name == "right"){
my_block.position += new Vector3(cam.Jump_Size, 0f);
}
else if (gameObject.transform.name == "up"){
my_block.position += new Vector3(0f, cam.Jump_Size);
}
else if (gameObject.transform.name == "down"){
my_block.position -= new Vector3(0f, cam.Jump_Size);
}
}
}
void Update()
{

}
}
Script Block.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Block : MonoBehaviour
{
public bool IsActive = false;
public Camera_s Camera_Script;
public int Id;
public int[] coords;
public int color;
private int[,,] grid;
void Start()
{
Camera_Script = GameObject.Find("Main Camera").GetComponent<Camera_s>();
Id = Camera_Script.Block_max + 1;
Camera_Script.Block_max += 1;
grid = Camera_Script.Grid;
grid[coords[0], coords[1], 0] = 1;
grid[coords[0], coords[1], 0] = color;
}
void OnMouseDown(){
IsActive = true;
Camera_Script.Active = Id;
Debug.Log("Active");
}
// Update is called once per frame
void Update()
{
if (Camera_Script.Active != Id){
IsActive = false;
}
}
}
Script Camera_s.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera_s : MonoBehaviour
{
public int Active = -1;
public int Block_max = -1;

public float Jump_Size;
public int[] Grid_Size;
public int[,,] Grid;
void Start()
{
Grid = new int[Grid_Size[1], Grid_Size[0], 2];
for (int i = 0;i < 3;i++){
for (int j = 0;j< 5;j++){
Grid[j, i, 0] = 0;
Grid[j, i, 1] = 0;
}
}
}
// Update is called once per frame
void Update()
{

}
}

我知道我的for出了问题,但我不知道如何解决。

代码的主要部分,其中我有错误:

for (int i = 0;i < 3;i++){
for (int j = 0;i < 5;j++){
Grid[j, i, 0] = 0;
Grid[j, i, 1] = 0;
}
}

Unity编辑器输入的数据:

Jump_Size=3f;网格大小=[5,3]

谢谢!

如果您输入的是真正的Grid_Size=[5,3],则意味着您的前两个维度被翻转。您可以简单地纠正这一点,但如果除了一个值对之外的任何东西都产生了错误,则不应该公开大小。

Grid = new int[Grid_Size[0], Grid_Size[1], 2];
for (int i = 0;i < Grid.GetLength(1);i++){
for (int j = 0;j< Grid.GetLength(0);j++){
Grid[j, i, 0] = 0;
Grid[j, i, 1] = 0;
}
}

如果翻转输入,但仍使用与以前相同的访问顺序,则会导致与以前一样的数组维度。当然,如何做到这一点取决于你想对数组做什么。

此外,最好检查输入的值是否正确,在块中,您将再次使用编辑器中的输入(坐标(对网格进行索引。我建议确保输入在数组的预期范围内

最新更新