Search Unity

Question How To Properly Instantiate UI Objects

Discussion in 'Prefabs' started by umityayla, Dec 14, 2020.

  1. umityayla

    umityayla

    Joined:
    May 21, 2019
    Posts:
    26
    Hello,

    There are times where we need to instantiate multiple prefabs instantly. Like leaderboard table that has around 100 elements. We usually instantiate them using coroutines like;

    Code (CSharp):
    1.     IEnumerator InstantiateStuff()
    2.     {
    3.         foreach(GameObject _gameObject in gameObjects)
    4.         {
    5.             yield return new WaitForSeconds(0.2f);
    6.             Instantiate(_gameObject, transform.parent);
    7.         }
    8.     }
    to prevent the main thread from freezing. But is there a more "proper" way to instantiate objects faster and more efficient way?

    Edit: We're aware of object pooling but due to memory restrictions, we can't use pooling option efficiently.
     
    Last edited: Dec 15, 2020
  2. kartik_unity

    kartik_unity

    Joined:
    Jan 14, 2020
    Posts:
    4
    I'm not sure about a better way to instantiate something like leaderboards in your case, I think that spawning them in a coroutine is not a bad way to go.

    I will say, however, that you should probably not do
    yield return new WaitForSeconds(0.2f);


    As far as I know that is creating a new object every time that code executes. You could save the wait for seconds object at the beginning of the routine
    WaitForSeconds wait = new WaitForSeconds(0.2f)

    and then say
    yield return wait;


    But that also feels like a long time to wait to spawn what should be pretty simple prefabs. Are you able to try just
    yield return null


    That would spawn one per frame- probably a lot faster if you're trying to spawn around 100 UI elements.