zoukankan      html  css  js  c++  java
  • 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可以克隆任何类型的物体,包括脚本。

  • 相关阅读:
    POJ-1947 Rebuilding Roads (树形DP+分组背包)
    HDU-1011 Starship Troopers (树形DP+分组背包)
    POJ-1155 TELE (树形DP+分组背包)
    HDU-1520 Anniversary party(树形DP)
    HDU-2196 Computer (树形DP)
    HDU-1561 The more, The Better (树形DP+分组背包)
    HDU-3853 LOOPS(概率DP求期望)
    POJ 1182(权值并查集,向量?)
    HDU 3038(权值并查集)
    POJ 1733(边带权并查集+离散化)
  • 原文地址:https://www.cnblogs.com/tgycoder/p/4952352.html
Copyright © 2011-2022 走看看