lundi 25 mai 2020

How to generate non-repeating Random Numbers in Unity

I am trying to create a simple Bingo game and want to make sure the numbers are not repeating on the bingo card. I have a random number generator, but for some reason the code I'm using doesn't work as the same numbers will constantly repeat. Could somebody please take a look at my code below and either tell me what I need to fix or fix the code for me?

public Grid(int width, int height, float cellSize)
{
    this.width = width;
    this.height = height;
    this.cellSize = cellSize;

    gridArray = new int[width, height];
    debugTextArray = new TextMesh[width, height];
    for (int x = 0; x < gridArray.GetLength(0); x++)
    {
        for (int y = 0; y < gridArray.GetLength(1); y++)
        {
            debugTextArray[x, y] = UtilsClass.CreateWorldText(gridArray[x, y].ToString(), null, GetWorldPosition(x, y) + new Vector3(cellSize, cellSize) * .5f, 20, Color.white, TextAnchor.MiddleCenter);
            Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x, y + 1), Color.white, 100f);
            Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x + 1, y), Color.white, 100f);
        }
    }
    Debug.DrawLine(GetWorldPosition(0, height), GetWorldPosition(width, height), Color.white, 100f);
    Debug.DrawLine(GetWorldPosition(width, 0), GetWorldPosition(width, height), Color.white, 100f);


    for (int x = 0; x <= 4; x++)
    {
        RandomValue(0, x);
        RandomValue(1, x);
        RandomValue(2, x);
        RandomValue(3, x);
        RandomValue(4, x);
    }

}

private Vector3 GetWorldPosition(int x, int y)
{
    return new Vector3(x, y) * cellSize;
}

public void RandomValue(int x, int y)
{

    if (x >= 0 && y >= 0 && x < width && y < height)
    {
        list = new List<int>(new int[Lenght]);

        for (int j = 0; j < 25; j++)
        {

            Rand = UnityEngine.Random.Range(1, 50);


            while (list.Contains(Rand))
            {
                Rand = UnityEngine.Random.Range(1, 50);

            }

            list[j] = Rand;
            gridArray[x, y] = list[j];
        }


        debugTextArray[x, y].text = gridArray[x, y].ToString();
        debugTextArray[2, 2].text = "Free";
    }
}

}




Aucun commentaire:

Enregistrer un commentaire