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 behind and activate a new segment at the end of the track. When this action takes place, there is a significant lag (1-2s). This lag is reduced to almost nothing when all the segments have been set active=true at least once.
Thinking that all segments must be rendered at least once, I set Update() to have everything 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 this lag?
Thanks in advance.
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.
Does the lag go away once you go through all 4 segments at least once?
Pre-instantiate and cycle
Enabling and disabling gameobjects is far cheaper than instantiate/destroy. Consider employing an object pool to take advantage of this.
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)
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.
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 everything had to be rendered first and “covered”, while waiting for user to click on a button to start.