- Home /
Put a prefab in Hierarchy without using Instantiate ? (from code)
Hello,
I was wondering if it was possible to put a prefab (as a game object and from code) in the scene without using Instantiate. I mean doing like a drag & drop but from code, without instantiating the prefab in c#. I know that when you put a prefab in the hierarchy by draging it with the mouse, it's not an instance.. I want to do the same but in C# (script). I tried to use new GameObject and set the prefab as a child but it causes an error (data corruption). Any idea ?
Thanks.
What do you mean it's not an instance when you drag and drop it?
I mean that I see nothing on the profiler when I drag and drop a prefab into the hierarchy BUT, I do see some action when I do it from code (Instantiate.Awake, produce, copy). I don't want to awake it or something, I just want to create it.
Answer by coolraiman · May 03, 2016 at 05:46 PM
you cant put the prefab in the scene, it will always be an instance of it.
the data corruption error mean that you are trying to modify the prefab and unity wont let you do that.
Also why would you want to avoid instancing a prefab? This is only a reference to the file in your assets, it virtually cost nothing
And finally, when you drag and drop a prefab in your hierarchy, it is an instance of the prefab.
The part with the reference is not true. it's an instance WITH a reference to the prefab, but its not ONLY a reference.
Easiest way to prove: if it would be only a reference every change made to the instance would automaticlly apply to the prefab which it doesnt, you have to click apply (which uses the reference to add the changes to the prefab)
Alright, but when I look into the Profiler, things are different when I instantiate a prefab from code and when I drag and drop it. Also, is there a way to set a prefab as a child of an empty object without modifying the prefab ? I want to avoid instantiating the prefab because I use GAF plugin (flash to Unity) and when I instantiate from code GAF generate a big spike 150$$anonymous$$B, GC alloc but when I just drop it with the mouse, GAF don't call some functions that cost a lot but only those which create the object (5$$anonymous$$B ins$$anonymous$$d of 150$$anonymous$$B). That's why I want to find a way to do the same as the drag and drop do but from code.
Answer by Ryanless · May 03, 2016 at 06:07 PM
ofc its an instance when you put something in the hierarchy. EVERYTHING in the hierarchy is ( and must be) an instance.
Little detail though, instantiate does cost a lot of cpu usage if you instantiate tons of object (like bullets). Then it becomes more effiecent to use a objectPooler. A great leason about objectPooling.
I know what polling is, this is not my problem here, I only want one object in my scene but using the same process as a drag and drop which obviously work as same as an instantiate. In my case, setActive cost a lot with the plugin I use.