Random Playing Cards Generation in Unity

Viewed 767

i am trying to create a simple texas hold'em poker game in unity, I have 52 sprites (images) of each card in a deck

i am trying to load player cards in the beginning of a round, (2 cards for each player) for n number of players all respective to 52 cards in the deck.

so what i am trying to do, is first generate a random number and then based on that number, i load the specific sprite but my unity freezes and nothing works and i am aware that this approach will not work if i replicate my Card Prefab which is bound with Get_Card Class, So i need another Approach. HELP thanks

Random Number Class

public class Random_Number
{
   const int n = 52;
    int[] all_num = new int[n];
    int number = 0;


    void Start()
    {

    for (int i = 0; i < n; i++)
    {
        all_num[i] = i;
    }

    }

    // Update is called once per frame
    void Update()
    {

    }

    public int get_me_a_number()
    {


        while (number == 0)
            {
            int rand = Random.Range(0, n);
            number = all_num[rand];
            all_num[rand] = 0;
            }

        Debug.Log(number.ToString());
        return number;
    }
}

Card Class

public class Get_Card : MonoBehaviour
{
    public Sprite[] Sprite_pic;
    int number;
    Random_Number number_class = new Random_Number();
    // Start is called before the first frame update
    void Start()
    {

            number = number_class.get_me_a_number();
            GetComponent<SpriteRenderer>().sprite = Sprite_pic[number];


    }

ISSUE is now fixed, Freezing issue was caused by an infinite loop.

2 Answers

in your case in class Random_Number

void Start()
{
    for (int i = 0; i < n; i++)
    {
        all_num[i] = i;
    }
}

is never called..so all_num is an array of Zero value (-> infinite loop in while)

i suppose you want to call it when the Class is instanciated

so i suggest you to declare a constructor:

public Random_number()
{
    for (int i = 0; i < n; i++)
    {
        all_num[i] = i;
    }
}

Start() and Update() is Unity event function, and will be called by unity automatically who inherits MonoBehaviour, and attached to active gameobject. In your code, your class Random_Number doesn't inherit Monobehaviour, so Start() is nothing more than just a method, which will never be called without the caller.

Because the default value of uninitialized int is 0 and Start() is never called, every element of all_num is zero. So when you call get_me_a_number(), what you are doing is just

while (0 == 0)
{
    // assign 0 to 0
}

Which is basically infinite-loop. That's why your unity stops.

Here's my suggestion: Initialize Random_Number with the explicit constructor:

public Random_number()
{
    for (int i = 0; i < n; i++)
    {
        all_num[i] = i;
    }
}
Related