简体   繁体   中英

How to fix Instantiate killing my performance

I am instantiating two sets of 50 GameObjects each.

private Enemy e1, 
              e2;

private Stack stack1, 
              stack2;


for(int i = 0; i < 50; i++)
    stack1.Push(Instantiate(e1));

for(int i = 0; i < 50; i++)
   stack2.Push(Instantiate(e2));

This code slows down my scene loading time. Is there a better way to do this?


Important Information

I use the objects right away after loading the scene. I store re use them throughout all my scenes so I never destroy them. Each object has very Little if any code in the Awake().

You could Instantiate the Objects right when your scene starts, deactivate them and only activate them when needed. That way you get the lag at the start when it is usually no problem to wait a couple of seconds.

Another way is to Instantiate GameObjects untill you reach a time Value in milliseconds that you set and then stop untill the next frame. This may or may not work depending on what you are doing.

If the actual objects you are instantiating are used frequently but only for a short duration you can do it like my first approach and reuse them when needed. Google "unity Object Pool" for that and you get a couple of good results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM