• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by loboclerk · Oct 17, 2013 at 11:26 AM · gameobjectinstantiatelagactive

Lag when activating GameObjects

I'm doing a simple script of a character running through a dynamically generated track, defined in segments. I have multiple instances of the segments instantiated in Start() with active=false, and have 4 segments active at any point of time.

Everytime the character crosses the end of 1 segment, I will deactivate the segment be$$anonymous$$nd and activate a new segment at the end of the track. When t$$anonymous$$s action takes place, there is a significant lag (1-2s). T$$anonymous$$s lag is reduced to almost not$$anonymous$$ng when all the segments have been set active=true at least once.

T$$anonymous$$nking that all segments must be rendered at least once, I set Update() to have everyt$$anonymous$$ng active=true when first called, and then as normal from the second time Update() is called. There is a much longer lag at the start (expected) but the lag still remains.

What else can I do to eliminate t$$anonymous$$s lag?

Thanks in advance.

Comment
JiMMaR
Shayan-1

People who like this

2 Show 12
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image loboclerk · Oct 18, 2013 at 12:51 AM 0
Share

This is the code that calls when the lag occurs. Not very optimized, but am quite sure the non-optimized bits won't cause this kind of lag.

Basically I use the "active" state of the gameobject to determine if it is available to be retrieved from the pool. GameObjectPool contains all the gameobjects that had been instantiated inside Start() and active=false.

Main issue is, the lag happens only ONCE for the same code. So if I have 10 road segment instances in the gameobject pool, it would lag 10 different times and subsequent calls will be much smoother.

"Generate Colliders" is unchecked in the imported model, does that mean no physics involved already?


Lag occurs when this is called the first time for each instance. I have run Debug.Log() to ensure that it is run only once inside Update() when supposed to. No accidental repetitions, hopefully.

 lastBuilding.transform.parent = null;
 lastBuilding.active = false;
 lastRoad.active = false;

 road = GetGameObject(TrackStraight);
 road.transform.position = newPosition;
 road.transform.localRotation = roadRotation;

 building = GetGameObject(buildingName);
 building.transform.parent = road.transform;
 building.transform.localRotation = Quaternion.identity;
 building.transform.localPosition = Vector3.zero;
 building.transform.localScale = Vector3.one;



 private GameObject GetGameObject(String resourceRef) {
     GameObject[] objList = GameObjectPool[resourceRef];
     int i;
     // largest objList to be traversed is 4
     for (i=0;i<objList.Length;i++) {
         GameObject obj = objList[i];
         if (obj.active==false) {
             obj.active = true;
             return obj;
         }
     }
     return null;
 }


Sample code to populate GameObjectPool, called once inside Start()

 objList = new GameObject[listSize];
 int i;
 for (i=0;i<listSize;i++) {
     obj = (GameObject)Instantiate(Resources.Load("Models/"+resourceRef));
     obj.active = false;
     objList[i] = obj;
 }
 GameObjectPool[resourceRef] = objList;
avatar image meat5000 ♦ · Oct 18, 2013 at 12:56 AM 0
Share

Lots of objects in objList?

avatar image loboclerk · Oct 18, 2013 at 01:10 AM 0
Share

Stated in the code that the largest objList is 4, not big I suppose?

avatar image meat5000 ♦ · Oct 18, 2013 at 01:13 AM 0
Share

Why does your function return null?

avatar image meat5000 ♦ · Oct 18, 2013 at 01:14 AM 0
Share

Basically, if its the first Inst that lags, why not inst before gameplay starts to initialise your pool?

Show more comments

5 Replies

· Add your reply
  • Sort: 
avatar image

Answer by loboclerk · Oct 21, 2013 at 03:05 AM

Thanks for everyone's inputs.

After several rounds of tests and alternatives, I'll list my conclusions here. Eventual result was smooth gameplay with additional user input initially.

  • Enabling and disabling the renderer had the best performance, compared to SetActive() and Instantiate/Destroy.

  • Lag on the first render of each GameObject instance could not be resolved, so everyt$$anonymous$$ng had to be rendered first and "covered", w$$anonymous$$le waiting for user to click on a button to start.

Comment
gabcvit
Shayan-1

People who like this

2 Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tubelightboy · Oct 28, 2020 at 05:58 PM 0
Share

I did not have this problem for some time and somehow when I was cleaning up my scripts, it crept in. I've tried all performance tweaks but none of em worked for this. The first lag for an object which renders initially... is it inevitable?

avatar image

Answer by $$anonymous$$ · Oct 17, 2013 at 01:33 PM

I would take a look at the way you're initializing your track segments. You may have some initialization code inside the Start method for each track segment that's causing the delay. If that's the case, then the delay makes sense since Start only runs if the script instance is enabled.

https://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.Start.html

Does the lag go away once you go through all 4 segments at least once?

Comment

People who like this

0 Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image $$anonymous$$ · Oct 17, 2013 at 03:56 PM 0
Share

Just re-read original question - it looks like the lag indeed goes away, so I would look at your Start() initialization code for each track.

avatar image loboclerk · Oct 17, 2013 at 05:07 PM 0
Share

Thanks for your comments. The lag happens when I deactivate 1 segment (and attached children) behind, and activate 1 segment in front. I will also activate some gameobjects (also from a pool), set position/rotation and attach them as child to the main segment.

The code that is being run is exactly the same each time, just that for each instance, the first time takes longer.

avatar image $$anonymous$$ · Oct 17, 2013 at 05:16 PM 0
Share

Could you post your object activation code from the Update() function? Maybe you're loading the same track multiple times?

avatar image loboclerk · Oct 18, 2013 at 12:58 AM 0
Share

Posted above! Ran Debug.Log() to make sure it wasn't run multiple times. If it did lag due to multiple calls, the lag wouldn't disappear after the first call for each instance?

avatar image

Answer by meat5000 · Oct 17, 2013 at 01:47 PM

Pre-instantiate and cycle

Enabling and disabling gameobjects is far cheaper than instantiate/destroy. Consider employing an object pool to take advantage of t$$anonymous$$s.

Comment

People who like this

0 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image loboclerk · Oct 17, 2013 at 05:09 PM 0
Share

Hi, sorry I did not make it clear above. I am coding my own object pool, that's why I am only activating/deactivating game objects instead of instantiating/destroying them. Unless I'm missing something here? (new to this)

avatar image meat5000 ♦ · Oct 17, 2013 at 06:43 PM 0
Share

Sounds right. Maaaaybe time to post some code?

avatar image

Answer by Chaosgod_Esper · Oct 17, 2013 at 01:59 PM

A 3rd approach is - add your model to a scene and save it from there as a prefab. I recognized that Prefabs are loaded much faster than a direct model (tested in my Dungeon keeper System)

Comment

People who like this

0 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image loboclerk · Oct 17, 2013 at 05:10 PM 0
Share

Thanks, will give it a shot and update!

avatar image loboclerk · Oct 18, 2013 at 03:54 AM 0
Share

I realize that by calling this, it is working effectively like a prefab. When the script is running, the generated gameobjects are all already indicated as (Clone). The performance difference then would only affect whatever's run in Start() and not in Update().

 Instantiate(Resources.Load(resourceRef));

In any case, I tried cloning prefabs explicitly and it was the same.

avatar image

Answer by whydoidoit · Oct 17, 2013 at 05:15 PM

I'd be guessing you have colliders in there. If the colliders don't have rigidbodies attached then they take a long time to make active at a new location. Attach kinematic rigidbodies to the colliders an it may help.

Comment

People who like this

0 Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image loboclerk · Oct 18, 2013 at 01:01 AM 0
Share

Actual instances were created inside Start() using

 Instantiate(Resources.Load(resourceRef));

Inside Unity Editor, Generate Colliders is unchecked for the imported model. I suppose with this, all physics for these objects would be off already, or am I missing something?

avatar image whydoidoit · Oct 18, 2013 at 01:12 AM 0
Share

So these sections have to colliders when you look at them in the editor?

avatar image loboclerk · Oct 18, 2013 at 01:20 AM 0
Share

I looked at the inspector when the code was running and clicked on the objects in the scene. None of them had any colliders or anything physics related. hmmm..

avatar image whydoidoit · Oct 18, 2013 at 01:27 AM 0
Share

You are setting and checking .active -> that should now be SetActive and activeInHierarchy presuming you are using Unity 4

avatar image loboclerk · Oct 18, 2013 at 01:50 AM 0
Share

Thanks for pointing that out. Changed all to SetActive and activeInHierarchy/activeSelf already. No change to performance unfortunately.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

19 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Best way to display scores appearance 1 Answer

Instantiating a gameobject causes a lagspike 2 Answers

Instantiate problem 1 Answer

GameObject Instantiated Off Camera 0 Answers

Do Asynchronous GameObject.Instantiate Exists? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges