DAY 18
0

## Instantiate實例化，用於將物件生成至場景中。(參考unity手冊)

``````//宣告建構式
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);
``````
• Object original ：生成物件，要複製的Object，可以是GameObject也可以是UI或其他物件。
• Transform parent：父物件(parent)，會將生成物件設定為該物件的子物件(child)。
• bool instantiateInWorldSpace：當生成於父物件底下時，可以選擇依照世界座標(true)還是父物件座標(false)生成。
• Vector3 position：Position for the new object. 設置Position，生成於此位置座標。
• Quaternion rotation：Orientation of the new object. 設置Rotation，生成於此旋轉角度。

※沒有要旋轉的時候，旋轉向量可以填這個：Quaternion.identity

## 實際例子1-生成

1.先創建好要複製的物件

2.寫好腳本，掛在空物件上

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InstantiateApple : MonoBehaviour
{
//宣告生成物件
public GameObject apple;
//設置三個生成位置
Vector3 position1 = new Vector3(-1.039978f,-0.330002f,0.0f);
Vector3 position2 = new Vector3(-0.039978f,-1.330002f,0.0f);
Vector3 position3 = new Vector3(-0.039978f,-0.330002f,0.0f);
//設置旋轉
Quaternion rotation1 = new Quaternion(0,0,0,0);

void Start()
{
Instantiate(apple,position1, rotation1);
Instantiate(apple,position2, new Quaternion(0,0,0,0));
Instantiate(apple,position3, Quaternion.identity);

}
``````

3.設定好之後執行

## 實際例子2-整理至父物件

1.做法都一樣，改腳本

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InstantiateApple : MonoBehaviour
{
//宣告要生成的物件
public GameObject apple;
//宣告生成物件的父物件
public Transform appleClass;
//三個生成位置
Vector3 position1 = new Vector3(-1.039978f,-0.330002f,0.0f);
Vector3 position2 = new Vector3(-0.039978f,-1.330002f,0.0f);
Vector3 position3 = new Vector3(-0.039978f,-0.330002f,0.0f);
//設置旋轉
Quaternion rotation1 = new Quaternion(0,0,0,0);

void Start()
{
Instantiate(apple,position1, rotation1,appleClass);
Instantiate(apple,position2, new Quaternion(0,0,0,0),appleClass);
Instantiate(apple,position3, Quaternion.identity,appleClass);

}
}
``````

2.結果