Possible Bug? GameObject.Instantiate copies instance instead of Prefab

Hi!

I am having trouble with spawning prefab instances from a script attached to that same prefab. Any changes I make to the instance gets are also present in any new prefab instances I create.

I am making an endless side scroller with some random items.
I have a prefab “Section” that I use for making new sections of the background as the player moves forward. I have a script on the Section prefab that spawns a new Section when the player enters a trigger zone in the section.
I also spawn some random flavour details in the section in Start().

The problem is that the details i spawn in the current instance also get added to the new Section instances that gets spawned in the trigger event. The first section spawned looks ok, but for each following section, all the previous detail items remain and new ones get added.

First I thought that the detail items I spawn in Start somehow get added to the Prefab and not just the instance. So when I later spawn a new section from the prefab, the new instance contains all the details from the current instance.

But if I look at the prefab in the editor while the game is running, it is clean, and doesn’t contain all the spawned items. So it seems the GameObject.Instantiate actually instantiates the current instance instead of the prefab I have assigned in the editor.

I can also see that if I click the SectionPrefab property in the editor, the instance of that prefab in the scene is highlighted, and not the prefab in the project browser.

Am I doing something wrong? Is this expected behaviour?

Is there a way to explicitly reference the prefab in the instantiate call?

My script looks something like this:

// Script attached to the Section prefab
class Spawner : MonoBehaviour

public Transform SectionPrefab; // Assigned the Section prefab in editor.
public Transform DetailPrefab; // Assigned in editor

Start()
  var detail = GameObject.Instantiate(DetailPrefab, MakeRandomPosition(), Quaternion.identity) as Transform; //Spawn detail item and add as child
  detail.parent = transform; // this should add the detail item to the current instance

OnTriggerEnter()
  // this should instantiate from the prefab
  // but actually instantiates the current instance instead
  var pos = new Vector3(transform.position.x + 100f, transform.position.y, transform.position.z);
  var newSection = GameObject.Instantiate(SectionPrefab, pos, Quaternion.identity); // Spawn new section from Prefab

Thanks,
Martin

Take another look at the Unity Script Reference.

Use the poly-parameter version of the function, like this:

public GameObject prefabObject;//assigned in editor
public GameObject cloneObject;

void CreateClone() {
     cloneObject = Instantiate(prefabObject, transform.position, Quaternion.identity);
}