Instantiate duplicates an object. Including all attached scripts and the entire hierarchy. It keeps references in the way you expect it: References to objects outside the cloned hierarchy will be left untouched, References to objects in the cloned hierarchy will map to the cloned object.
Instantiate is incredibly fast and very versatile. It is essential to using Unity to its fullest.
For example here is a tiny script that when attached to a rigidbody with collider will destroy itself and instead spawn an explosion object
var explosion : Transform;
// When a collision happens destroy ourselves
// and spawn an explosion prefab instead
function OnCollisionEnter () {
Destroy (gameObject);
var theClonedExplosion : Transform;
theClonedExplosion = Instantiate(explosion,
transform.position, transform.rotation);
}
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public Transform explosion;
void OnCollisionEnter() {
Destroy(gameObject);
Transform theClonedExplosion;
theClonedExplosion = Instantiate(explosion, transform.position, transform.rotation) as Transform;
}
}
import UnityEngine
import System.Collections
class example(MonoBehaviour):
public explosion as Transform
def OnCollisionEnter():
Destroy(gameObject)
theClonedExplosion as Transform
theClonedExplosion = (Instantiate(explosion, transform.position, transform.rotation) as Transform)
Instantiate is usually used in conjunction with Prefabs.