简体   繁体   中英

How to use 2D GameObject array as a parameter in a c# function ( 2D unity game)

I'm a newbie at unity/c#, and i'm coding a 2D chess game using unity, and i'm having some trouble making functions. I'm trying to setup a function that renders pieces on the board, but i can't seem to make it work. I want to use 2D array as a third parameter in this function but I keep getting this error: error CS1503: Argument 3: cannot convert from 'UnityEngine.GameObject' to 'UnityEngine.GameObject[,]' . This is my board class:

void Start()
{
    boardScript = GameObject.FindGameObjectWithTag("BoardScript").GetComponent<Board>();
    spawn = GameObject.FindGameObjectWithTag("GameController").GetComponent<SpawnPieces>();

    boardScript.createBoard();
}

This is one of my piece classes:

public void spawnQueen(int x, int y, GameObject[,] board)
{
    if (x == 3 && y == 0)
    {
        board[x, y] = Instantiate(whiteQueen, new Vector3(x * 4.49f, y * 4.49f, -1), Quaternion.identity);
    }
    else if (x == 3 && y == 7)
    {
        board[x, y] = Instantiate(blackQueen, new Vector3(x * 4.49f, y * 4.49f, -1), Quaternion.identity);
    }
}

And this is the class that will render the pieces:

public void spawnPiece()
{
    boardScript = GameObject.FindGameObjectWithTag("BoardScript").GetComponent<Board>();
    GameObject[,] boardArray = boardScript.board;

    rookScript = GameObject.FindGameObjectWithTag("RookScript").GetComponent<RookScript>();
    pawnScript = GameObject.FindGameObjectWithTag("PawnScript").GetComponent<PawnScript>();
    kingScript = GameObject.FindGameObjectWithTag("KingScript").GetComponent<KingScript>();
    bishopScript = GameObject.FindGameObjectWithTag("BishopScript").GetComponent<BishopScript>();
    kinghtScript = GameObject.FindGameObjectWithTag("knightScript").GetComponent<knightScript>();
    queenScript = GameObject.FindGameObjectWithTag("QueenScript").GetComponent<QueenScript>();

    for (int x = 0; x < 8; x++)
    {
        for (int y = 0; y < 8; y++)
        {
            rookScript.spawnRook(x, y, boardArray[x, y]);
            pawnScript.spawnPawn(x, y, boardArray[x, y]);
            knightScript.spawnKnight(x, y, boardArray[x, y]);
            kingScript.spawnKing(x, y, boardArray[x, y]);
            queenScript.spawnQueen(x, y, boardArray[x, y]);
            bishopScript.spawnBishop(x, y, boardArray[x, y]);
        }
    }
}

As I have mentionned I am new to C#, any help would be appreciated.

With the way you call your method you are passing an element of the boardArray instead of the whole array. Try calling the method like this:

bishopScript.spawnBishop(x, y, boardArray);

Notice the third argument is boardArray as opposed to boardArray[x, y] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM