Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Unity freezes when I'm using "while" loop

Discussion in 'Editor & General Support' started by DangerKiddy, Nov 15, 2020.

  1. DangerKiddy

    DangerKiddy

    Joined:
    Feb 29, 2020
    Posts:
    8
    Hi, i've added this code in void Start() :

    Code (CSharp):
    1. int[] p = new int[256];
    2.         for (int i = 0; i < 256; i++)
    3.         {
    4.             int val = Random.Range(0, 255);
    5.  
    6.             while (System.Array.Exists(p, element => element == val))
    7.             {
    8.                 val = Random.Range(0, 255);
    9.             }
    10.             p[i] = val;
    11.         }
    and then my unity just freezes and I have no idea what to do. Point is generate array with numbers, which are "unique"
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,336
    Your while loop condition is never clearing: you are never changing what is inside it.

    When your scripts run you have 100% of the power. If you don't return, Unity will never again run.

    If you want to run this over a few frames, make a coroutine. If you REALLY must, make it a thread, but I highly recommend NOT using threading unless there is no other way. You buy yourself a LOT of headaches with threading.

    Here is some timing diagram help:

    https://docs.unity3d.com/Manual/ExecutionOrder.html

    If you're just looking to shuffle 256 things (my first-glance speculation about what the above code might do), then just use a Fisher Yates shuffle on a preloaded deck and it will be far more performant and reliable.
     
    Last edited: Nov 15, 2020
    Vryken likes this.
  3. DangerKiddy

    DangerKiddy

    Joined:
    Feb 29, 2020
    Posts:
    8
    Okay, thank you!