Can someone explain Instantiation to a beginner?

Hey guys,

So, I looked at all the examples I could find online, the documentation, watched videos and… I still don’t get it. How does instantiation work - specifically, the method Instantiate()?

This is the code I wrote in my attempt to just make instantiation work on one of my prefabs - I just want to create copies of my CustomerPrefab:

using UnityEngine;
using System.Collections;

public class CustomerScript : MonoBehaviour {

	public GameObject CustomerPrefab;

	void Update () {
	 Instantiate (CustomerPrefab, new Vector3(0,0,0), Quaternion.identity);
}
}

This script is attached to my CustomerPrefab and there’s no errors, but it doesn’t do anything. I understand that they would all spawn in the same spot (0, 0, 0) but for now, I can’t even make it spawn one.

So first off - when you make a new GameObject in the top, does it have to refer to the prefab that I want to copy? If not, then how does Instantiate() know which prefab to copy?
And secondly, the first parameter in Instantiate, what is that even? The documentation says “original” and I would assume that means the original GameObject to be Instantiated, right? But how do you make it refer to a prefab and have it create 5 instances of the prefab?

Michael

Hi!! The manual linked below is a bit meaty but it is definitely worth a read. It will answer all of your questions and provide you with a good foundation to build on :smiley: Best of luck!!!

Manual On Instantiating Prefabs

In your example. you’ve got the public variable “CustomerPrefab”. Don’t get confused here, you can attach the script to any object as the variable does not refer to the game objects name that it is attached to, but rather to a game object that is assigned to the variable.
You can either assign it via code or, since it is public, assign it via the inspector. For that, you click onto the game object that this script is attached to (this can be any, your camera, a light, a UI object… just everything), and drag&drop your prefab from the project folder into the slot that appeared in the inspector.