Update a prefab before it's initially calculated on instantiation?
I have a small prefab that is a progress bar that displays a value, label via TextMeshPro and obviously a progress bar which is just a filled image. I programmatically instantiate this prefab and set it's values vias code.
The problem is that behind the scenes UI calculations are performed twice. Once when the prefab is instantiated, with the sizes, labels etc all as they were when the prefab was designed. Then again when I set the values of the prefab instance.
Sure you'll never see these initial values, but nevertheless there's calculations going on behind the scenes for fonts etc that is just wasted CPU cycles.
It's almost as if you can pass values into a prefab constructor.. or tell it not to do ANY calculations/ rasterization of fonts, etc until you tell it?
Maybe it doesn't work like that and uses a "dirty" flag and does the calculations on the first frame it needs to be displayed? I just dont know.
Some clarification would be nice.
Answer by Soraphis · Feb 24, 2019 at 12:02 AM
well this post is a bit dated, but its not outdated, so I'll just answer it:
before i'm going to answer your question a word of warning:
Sure you'll never see these initial values, but nevertheless there's calculations going on behind the scenes for fonts etc that is just wasted CPU cycles.
what you're doing is premature optimization / micro-optimatzions. spending time on stuff like this is wasted time, unless you're instantiating 20+ progressbars each frame. optimize your Update/FixedUpdate methods. don't render stuff that is not visible. don't allocate memory if you don't have to (so the GC won't bother you). and always use the profiler before optimization, so you know where to optimize for the best benefit.
to answer your question:
if you call Instantiate the gameobject is not immediately instantiated or rendered. but you instantly get a reference to the GO. just make all those changes you'd make right after the instantiation. the gameobject is initialized before the next frame, it will use those new values then.
While Awake is called before your changes apply, Start will have those changes, and Start is called before the first Update method on the object is called -> before it renders the first time.
alternatively:
disable the prefab before instantiation. this will make the gameobject instantiate disabled, do your changes to the components and enable it. in this case the awake method will have the updated values, too.
again: always use the profiler before optimization. don't trust anybody, test/benchmark stuff yourself.
edit: this site has the worst markdown renderer ever -.-