- Home /
Preloading / Caching Prefabs [Unity iPhone]
The first time I Instantiate prefabs in my game (particularly ones that use large bitmap textures) there is a noticeable lag / delay before they appear, subsequent times after this they then appear instantly. Is the best way of dealing with this to Instantiate then Destroy all the problematic assets before first gameplay?
ChrisError
Answer by duck · Nov 17, 2009 at 11:33 AM
A useful technique for iPhone is to instantiate things that you'll need for your gameplay during your menu screens, so that by the time the user clicks 'play', everything has already been preloaded.
Also, wherever possible, re-use a pool of instantiated objects rather than destroying and then re-creating objects each time new ones are required.
Also you should spread out your instantiation over a number of frames, so that there isn't a large hiccup caused by a number of items being instantiated all during the same update.
You might find you need to write some kind of instantiaton manager, which handles instantiating a queue of items over a number of frames.
Answer by equalsequals · Nov 26, 2009 at 09:43 PM
To add to Duck's comment,
With iPhone the garbage collection is a bit tricky. Even if you destroy the only instance of an object, garbage collection can neglect to clean it up. In a previous project we found that several "destroyed" Game Objects were still in memory after dumping old scenes and loading new ones.
We found the only way to truly destroy dynamically instantiated objects was to do the following:
Destroy(myObj);
myObj = new GameObject();
This will let GC know that you are using that variable for something else now and that it is safe to be collected.
As loginstubbornmoose's question went unnoticed, I'd like to ask the same... because your example would instantiate a new GameObject which should be avoided if possible, no?
Answer by stubbornmoose · Nov 27, 2009 at 03:31 PM
Will it help to GC if we do this?
Destroy(myObj);
myObj = null;
Thanks
Answer by equalsequals · Jan 08, 2010 at 08:12 PM
To answer SisterKy:
Yes, you do want to avoid this in most cases. This is just the solution I found for a very specific case.
To explain, when developing for iPhone my team found that memory remained allocated after GC passes even though the object had been destroyed. As an important note I should mention that the GameObject in question was dynamically instantiated from Resources.Load(), not manually instantiated via the Editor.
We tried setting all references to the object to null, but this made no difference to the memory as per Instruments' readout. What we discovered was that if we immediately instantiated a blank object in place of the destroyed object, GC did pick it up and memory was freed.
Does that clear it up at all?
==