Unity 版本 5.6.x
Object.Instantiate 几种调用方法
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Transform parent);
public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
Parameters 参数
参数 | 说明 |
---|---|
original | 一个物体,已经存在的(比如一个prefab),你想实例化它的一个复制 |
position | 要生成的新物体的Position属性 |
rotation | 要生成的新物体的Rotation属性 |
parent | 这个新物体的父级 |
instantiateInWorldSpace | 如果是true的话,新的物体的坐标将保持为世界坐标。为false的话,新物体的坐标将附着于其父物体(即局部坐标)。 |
Returns 返回值
返回你想实例化的那个物体的克隆。
Description 描述
对 original 物体进行克隆,并返回这个克隆的新物体。
这个方法对物体进行克隆,就像在编辑器里直接对物体进行 Duplicate 即复制操作一样。如果你克隆的是一个 GameObject ,你可以选择性地设置它的 position 和 rotation(默认使用这个原始 GameObject 的 position 和 rotation)。如果你克隆的是一个 Component ,那么它所附属于的 GameObject 也会被克隆,并且同样的你可以选择性的设置它的属性。
当你克隆一个 GameObject 或者 Component 时,它的所有子物体以及组件也会被克隆,并且与元物体属性一致。
新的克隆出的物体默认是没有父级物体的,所以它不会是元物体的“sibling”即兄弟物体。然而,你仍然可以使用重载方法中的一种对新物体指定其父物体。如果指定了父物体,且同时没有指定 rotation 和 positon的话,元物体的 rotation 和 position 就将是新物体的局部 rotation 和 position(但若 instantiateInWorldSpace 为 true 的话,将会是新物体的世界 rotation 和 position。)
如果元物体的状态是 inactive,则新物体的状态也将是 inactive。
// 实例化 10 个该 prefab 的克隆,每两个之间都间隔一定的距离。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Transform prefab;
void Start()
{
for (int i = 0; i < 10; i++)
{
Instantiate(prefab, new Vector3(i * 2.0F, 0, 0), Quaternion.identity);
}
}
}
Instantiate 方法最常用来实例化子弹、AI敌人、粒子爆炸或破坏物体的替代品。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Rigidbody projectile;
void Update() {
if (Input.GetButtonDown("Fire1")) {
Rigidbody clone;
clone = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(Vector3.forward * 10);
}
}
}
Instantiate 方法也可以直接克隆脚本(script)实例。整个物体的 Hierarchy 将会被克隆,且克隆的脚本实例将被返回。
using UnityEngine;
using System.Collections;
public class Missile : MonoBehaviour
{
public int timeoutDestructor;
// ...other code...
}
public class ExampleClass : MonoBehaviour
{
// Instantiate a prefab with an attached Missile script
public Missile projectile;
void Update()
{
// Ctrl was pressed, launch a projectile
if (Input.GetButtonDown("Fire1"))
{
// Instantiate the projectile at the position and rotation of this transform
Missile clone = (Missile)Instantiate(projectile, transform.position, transform.rotation);
// Set the missiles timeout destructor to 5
clone.timeoutDestructor = 5;
}
}
}
克隆物体后,你可以使用 GetComponent 方法来为克隆后的物体设置属性。