mercredi 4 juillet 2018

fisher yates method for random with unity. and i get this error IndexOutOfRangeException: Array index is out of range.

i am create game puzzle in unity. and using fisher yates shuffle for random the puzzle piece. I am get this error IndexOutOfRangeException: Array index is out of range.

public int m_randomLooping = 2;
int[] puzzle1 = { 0,1,2 }; 
private int m_size = 3;

void Shuffle(int[] a)
{
    // Loops through array
    for (int i = a.Length-1; i > 0; i--)
    {
        // Randomize a number between 0 and i (so that the range decreases each time)
        int rnd = Random.Range(0,i);

        // Save the value of the current i, otherwise it'll overright when we swap the values
        int temp = a[i];

        // Swap the new and old values
        a[i] = a[rnd];
        a[rnd] = temp;
    }


}    

void RandomizePlacement (){
    VectorInt2[] puzzleLocation = new VectorInt2[2];
    Vector2[] puzzleOffset = new Vector2[2];

    do {

        for (int i = 0; i < m_randomLooping; i++) {
            Shuffle(puzzle1);

            puzzleLocation [0].x = puzzle1[i];// if i change this puzzle[i]; to Random.Range (0, m_size); its works, but I want to use fisher yates for random
            puzzleLocation [0].y = puzzle1[i];
            puzzleLocation [1].x = puzzle1[i];
            puzzleLocation [1].y = puzzle1[i];

            puzzleOffset [0] = m_puzzle [puzzleLocation [0].x, puzzleLocation [0].y].GetImageOffset ();
            puzzleOffset [1] = m_puzzle [puzzleLocation [1].x, puzzleLocation [1].y].GetImageOffset ();

            m_puzzle [puzzleLocation [0].x, puzzleLocation [0].y].AssignImage (puzzleOffset [1]);
            m_puzzle [puzzleLocation [1].x, puzzleLocation [1].y].AssignImage (puzzleOffset [0]);


        }
    } while (CheckBoard() == true);


}

where is my mistake ? please help me for fix this code... thanks




Aucun commentaire:

Enregistrer un commentaire