Onject.Instantiate实例

该函数有两个函数原型:

  1. Object Instantiate(Object original,Vector3 position,Quaternion rotation);
  2. Onject Instantiate(Object original);

对于第一个来说,是指克隆原始物体并返回该克隆物体。其位置是position,旋转位置是rotation,如果克隆的是一个游戏物体,那么该游戏体的组件或者脚本实例都将被传入,会将整个游戏包含的字对象以及层次克隆出来。

下面是Unity API给出的一个例子:

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    public Rigidbody projectile;
    void Update() {
        if (Input.GetButtonDown("Fire1")) {
            Rigidbody clone;
            clone = Instantiate(projectile, transform.position, transform.rotation);
            clone.velocity = transform.TransformDirection(Vector3.forward * 10);
        }
    }
}// Instantiate a rigidbody then set the velocity
//实例化一个刚体,然后设置速度
var projectile : Rigidbody;

function Update () {
    // Ctrl was pressed, launch a projectile
    //按Ctrl发射炮弹
    if (Input.GetButtonDown("Fire1")) {
        // Instantiate the projectile at the position and rotation of this transform
        //在该变换位置和旋转,实例化炮弹
        var clone : Rigidbody;
        clone = Instantiate(projectile, transform.position, transform.rotation);

        // Give the cloned object an initial velocity along the current object's Z axis
        //沿着当前物体的Z轴给克隆的物体一个初速度。
        clone.velocity = transform.TransformDirection (Vector3.forward * 10);
    }
}

对于第二个函数来说,保留被克隆物体的位置和旋转。这实际上等同于在Unity使用(duplicate)复制命令,如果物体是一个Component 或GameObject,整个游戏物体包含所有组件将被克隆,如果游戏物体有一个transform,所有子物体将被复制。所有游戏物体克隆之后被激活。

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    public Transform prefab;
    void OnTriggerEnter() {
        Instantiate(prefab);
    }
}// Instantiates prefab when any rigid body enters the trigger.
// It preserves the prefab's original position and rotation.
//当任何刚体进入触发器时实例化prefab
//它保留prefab的原始位置和旋转
var prefab : Transform;

function OnTriggerEnter () {
    Instantiate (prefab);
}

需要注意的是Instantiate可以克隆任何类型的物体,包括脚本。

原文地址:https://www.cnblogs.com/tgycoder/p/4952352.html