数组索引不超出范围,但应定义.编程的新手



第一个文章。

我正在自我教育C#和Unity,并从事类似于Bejeweled的" Match-3"风格游戏。我已经根据教程编写了下面发布的所有代码,但是评论部分中的我本人和其他人都有问题。

编译器所说的错误。

IndexOutOfRangeException: Array index is out of range.
CreateGame.CheckGrid () (at Assets/Scripts/CreateGame.cs:181)
CreateGame.Update () (at Assets/Scripts/CreateGame.cs:229)

createGame.cs的完整代码(整个项目中唯一的脚本)粘贴在下面。但是,为了帮助您,我可以说,从我从索引中研究的内容中,每当您搜索阵列中未存储的东西时,就会发生。成为C#的全新,只有2个项目(也来自教程),我缺乏有关如何实际解决此问题的技术知识。

从我的理解中,当数组何时何时少于0(例如负值)编译器将返回此错误,因为-1显然超出了范围。

我相信罪魁祸首是与这些陈述有关的,特别是我们从c整数中减1的地方。

if (tiles[c, r] != null && tiles[c - 1, r] != null)

但是,上面的嵌套在此内部以进行语句

for (int c = 0; c < cols; c++)

因此,c的值永远不要小于零,或者我误解了该语句的逻辑,c在0开始,然后如果少于cols变量,则添加1,或者首先完成该词对于c = 0时循环。我不确定如何解决此问题。

还值得一提的是,数组大小是在我正在工作的场景中的gameObject(在检查器中)定义的,AS 4,我有4个单独的对象预制到分配给瓷砖数组的4个值,并将其位置存储在图块数组中(如代码中)。另外,CS脚本仅附加到一个游戏对象上,因此没有多个代码运行的实例。

对不起,如果这不太有井井有条,或者我已经学习了一个星期。

感谢您的查看!:)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile
{
    public GameObject tileObj;
    public string type;
    public Tile(GameObject obj, string t)
    {
        tileObj = obj;
        type = t;
    }
}
public class CreateGame : MonoBehaviour
{
    GameObject tile1 = null;
    GameObject tile2 = null;
    public GameObject[] tile;
    List<GameObject> tileBank = new List<GameObject> ();
    static int rows = 8;
    static int cols = 8;
    bool renewBoard = false;
    Tile[,] tiles = new Tile[cols, rows];
    void Start()
    {
        //List population
        int numCopies = (rows * cols) / 3;
        for (int i = 0; i < numCopies; i++)
        {
            for(int j = 0; j < tile.Length; j++) // J becomes the int = to number of tile prefabs added
            {
                GameObject o = (GameObject)Instantiate 
                    (tile [j], new Vector3 (-10, -10, 0), tile [j].transform.rotation); // creates a clone tile of the screen
                o.SetActive (false);
                tileBank.Add (o); // adds tile (game object called o) to the array (not shuffled)
            }
        }
        ShuffleList(); //Shuffles the list of tile-bank after the list has been populated
        //Populates rows and columns with tiles from tileBank array
        for (int r = 0; r < rows; r++)
        {
            for (int c = 0; c < cols; c++)
            {
                Vector3 tilePos = new Vector3 (c - 2, r - 4, 0); //creates tiles with an offset ( -2x and -4y) to place them in scene
                for (int n = 0; n < tileBank.Count; n++)
                {
                    GameObject o = tileBank [n];
                    if (!o.activeSelf) // if the tile is not active move it and make it active
                    {
                        o.transform.position = new Vector3 (tilePos.x, tilePos.y, tilePos.z); //moves tile into position, it was stored inactive at -10,-10
                        o.SetActive (true);
                        tiles[c, r] = new Tile (o, o.name); //Stores tile back into array
                        n = tileBank.Count + 1; //Update tile count
                    }
                }
            }
        }
    }
    //Shuffles the order of the array storing the tiles
    void ShuffleList()
    {
        System.Random rand = new System.Random ();
        int r = tileBank.Count;
        while (r > 1)
        {
            r--;
            int n = rand.Next (r + 1);
            GameObject val = tileBank [n];
            tileBank [n] = tileBank [r];
            tileBank [r] = val;
        }
    }
    //checks for missing tiles and adds new ones from array, also drops tiles down if there is an opening
    void RenewGrid()
    {
        bool anyMoved = false;
        ShuffleList ();
        for (int r = 1; r < rows; r++)
        {
            for (int c = 0; c < cols; c++)
            {
                if (r== rows - 1 && tiles[c, r] == null)
                    //if in the top row and there are no tiles
                {
                    Vector3 tilePos = new Vector3 (c, r, 0);
                    for (int n = 0; n < tileBank.Count; n++)
                    {
                        GameObject o = tileBank [n];
                        if (!o.activeSelf)
                        {
                            o.transform.position = new Vector3 (tilePos.x, tilePos.y, tilePos.z);
                            o.SetActive (true);
                            tiles [c, r] = new Tile (o, o.name);
                            n = tileBank.Count + 1;
                        }
                    }
                }
                if (tiles[c, r - 1] != null)
                {
                    if (tiles[c, r - 1] == null)
                        //drop down if space below is empty
                    {
                        tiles [c, r - 1] = tiles [c, r];
                        tiles [c, r - 1].tileObj.transform.position = new Vector3 (c, r - 1, 0);
                        tiles [c, r] = null;
                        anyMoved = true;
                    }
                }
            }
        }
        if (anyMoved)
        {
            Invoke ("RenewGrid", 0.5f);
        }
    }

    void CheckGrid()
    {
        int counter = 1;
        //check in columns for matches
        for (int r = 0; r < rows; r++) //repeats function until you have satisfied the number of rows
        {
            counter = 1;
            for (int c = 1; c < cols; c++)
            {
                if (tiles[c, r] != null && tiles[c - 1, r] != null) //if the tiles exist (not null)
                {
                    if (tiles[c, r].type == tiles [c - 1, r].type) //if there is a match add 1 to the counter for match checks
                    {
                        counter++;
                    }
                    else
                    {
                        counter = 1; //reset counter
                    }
                    //if a match is found remove tiles
                    if (counter == 3)
                    {
                        if (tiles [c, r] != null)
                        {
                            tiles [c, r].tileObj.SetActive(false);
                        }
                        if (tiles [c - 1, r] !=null)
                        {
                            tiles [c - 1, r].tileObj.SetActive(false);
                        }
                        if (tiles [c - 2, r] !=null)
                        {
                            tiles [c - 2, r].tileObj.SetActive(false);
                        }
                        tiles[c , r] = null; // changes values to null in the 2D matrix
                        tiles[c - 1, r] = null;
                        tiles[c - 2, r] = null;
                        renewBoard = true;
                    }
                }
            }
        }
        //check in rows for matches
        for (int c = 0; c < cols; c++)
        {
            counter = 1;
            for (int r = 1; c < rows; r++)
            {
                if (tiles[c, r] != null && tiles[c - 1, r] != null) //if the tiles exist (not null)
                {
                    if (tiles[c, r].type == tiles [c - 1, r].type) //if there is a match add 1 to the counter for match checks
                    {
                        counter++;
                    }
                    else
                    {
                        counter = 1; //reset counter
                    }
                    //if a match is found remove tiles
                    if (counter == 3)
                    {
                        if (tiles [c, r] != null)
                        {
                            tiles [c, r].tileObj.SetActive(false);
                        }
                        if (tiles [c, r - 1] !=null)
                        {
                            tiles [c, r - 1].tileObj.SetActive(false);
                        }
                        if (tiles [c, r - 2] !=null)
                        {
                            tiles [c, r - 2].tileObj.SetActive(false);
                        }
                        tiles[c, r] = null; // changes values to null in the 2D matrix
                        tiles[c, r - 1] = null;
                        tiles[c, r - 2] = null;
                        renewBoard = true;
                    }
                }
            }
        }
        if(renewBoard)
        {
            RenewGrid();
            renewBoard = false;
        }
    }
    void Update()
    {
        CheckGrid ();
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); //casts a ray from mouse position
            RaycastHit2D hit = Physics2D.GetRayIntersection (ray, 1000); //tests for ray hit
            if (hit)
            {
                tile1 = hit.collider.gameObject; //changes tile1 null to the gameObject who's collider was hit
            }
        }
        // if mouse button up detected after an initial tile has been hit with ray
        else if (Input.GetMouseButtonUp(0) && tile1)
        {
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            RaycastHit2D hit = Physics2D.GetRayIntersection (ray, 1000);
            if (hit)
            {
                tile2 = hit.collider.gameObject; //changes tile2 nulle to the gameObject who's collider was hit
            }
            if (tile1 && tile2) //If we has two tile values clicked, swap them
            {
                //check to see that distance of clicked tiles is not greater than 1 tile
                int horzDist = (int)Mathf.Abs (tile1.transform.position.x - tile2.transform.position.x);
                int vertDist = (int)Mathf.Abs (tile1.transform.position.y - tile2.transform.position.y);
                if (horzDist == 1 ^ vertDist == 1) // X-OR Statment, IF 1 , OR 1, but NOT BOTH
                {
                    //get tile 1's array position
                    Tile temp = tiles [(int)tile1.transform.position.x, (int)tile1.transform.position.y];
                    //change tile 1's array position to now be tile 2's array position
                    tiles [(int)tile1.transform.position.x, (int)tile1.transform.position.y] = 
                    tiles [(int)tile2.transform.position.x, (int)tile2.transform.position.y];
                    //change tile 2's array position to now be tile 1's old array position
                    tiles [(int)tile2.transform.position.x, (int)tile2.transform.position.y] = temp;

                    Vector3 tempPos = tile1.transform.position; //get tile 1's GameObject position
                    tile1.transform.position = tile2.transform.position; //change tile 1 to tile 2's GameObject position
                    tile2.transform.position = tempPos; //change tile 2 to tile 1's GameObject position
                    //reset clicked tiles
                    tile1 = null;
                    tile2 = null;
                }
                else
                {
                    GetComponent<AudioSource> ().Play (); // Play error sound when illegal swap attempted
                }
            }
        }
    }
}

错误仅仅是用于语句中的错误变量。
for (int r = 1; c < rows; r++)
应该是
for (int r = 1; r < rows; r++)

最新更新