- Home /
Is an object created when dragging a prefab to a GameObject script field
I have a simple script:
public Test : MonoBehaviour
{
public GameObject prefab;
}
When dragging a prefab to the prefab field of this script in the Inspector, is a gameobject instance being created automatically by unity?
It seems to me that GameObject is used to represent both a "template" / prefab and a runtime object that was created.
Is there any distinction between the two ? what happens in this case exactly ?
It seems to me that GameObject is used to represent both a "template" / prefab and a runtime object that was created.
Here you are discovering the wonders of OOP. Google polymorphism at some point.
Answer by Kiwasi · Jul 02, 2014 at 12:31 AM
Short answer is no, long answer follows.
As I understand it any prefab that is referenced in your scene is loaded into memory when your scene loads. So yes, there is a memory cost to having a prefab assigned, weather you instantiate it or not. Any referenced prefabs will also be included in the build. So don't assign prefabs you don't intend to use.
On the other hand the data that is being passed to your script is just a reference. Once you have assigned the reference once there is no appreciable cost of assigning the reference to multiple scripts. You are just creating a reference to memory that was already allocated when the scene was loaded.
When you call instantiate you create the actual instance of the GameObject. Then memory is allocated to create you instance.
I'm also pretty sure Unity has some optimisation tricks happening behind the scenes. A prefab might use less memory then an actual instance of the GameObject.
Your answer
Follow this Question
Related Questions
Prints correct on console but not updating on Prefab/Gameobject. 2 Answers
Prefab not inheriting GameObject when instantiated 1 Answer
How to create and save a gameobject to a prefab with a script 3 Answers
Calling script on prefab using array of prefabs. 1 Answer
Staged Prefab can't "Apply" after adding using Gameobject as a variable 1 Answer