I’m iterating through a set of prefabs and instantiating them. After each one is created, I parent it to a container. This worked perfectly under 3.5. However, after upgrading to 4.0, Unity froze (beachballed) each time I ran the app.
I tracked it down to the parenting of these GameObjects. Basically, the stripped down C# code is this:
for(int d = 0; d < plano.frontsDeep; d++)
{
GameObject productObj = Instantiate(plano.prefab, pos, rot) as GameObject;
...
if(container != null)
productObj.transform.parent = container.transform;
}
I have come up with a roundabout solution, by just referencing the parent transform in the GameObject script, and setting the parent in it’s Start() function. However, I’m perplexed as to why this is happing in the first place, when it was working flawlessy in 3.5? I’m thinking maybe I was lucky it worked in 3.5, and I should in fact wait a frame before accessing the transform.
That’s what it boiled down to after commenting out everything else. It should work, but in my case it doesn’t (in Unity 4.0). So, I guess I need to know:
Why was it working before and not now in Unity 4
Why, when I parent in the objects Start() function instead, it works?
Another theory… Just thinking off the top of my head; Particularly, if it’s working in your case…
I’m wondering if the code snippet there isn’t actually the problem, but there’s something underlying that is no longer being set up that I’m using somewhere else in the code that is now in an unusable state, until the next frame.
I reported a very similar bug about two weeks ago. It’s still open. Does it only happen in the build or does the editor crash as well? My problem was, that after upgrading to Unity 4, certain prefabs instantly crashed the build when being instantiated (hierarchies and parenting is involved too). My conclusion was that whatever Unity instantiates isn’t what I specified to be instantiated. So for example the Player who shoots a rocket doesn’t instantiate a rocket but some random transform from the same hierarchy, which seems to crash Unity builds right away. And this only happens in Unity 4 builds, everything in the editor works. All very strange.
I must admit, at this stage I was only running in the Editor. Went through a painstaking commenting out and back in again to locate what was actually causing it!
By moving parenting to the GO’s Start() function seems to work though.