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 ?
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.