Menu
CoddyTech

PrefabとInstantiate

CoddyのUnityジャーニー「Unityスクリプトの基礎」セクションの一部。レッスン 62/85。

プレハブはテンプレートとして保存されたGameObjectです。HierarchyからオブジェクトをProjectウィンドウにドラッグすると、UnityはそのすべてのコンポーネントとInspectorの値を保存します。プレハブ自体はシーン内にはありません。ほかの参照と同じように、フィールドを通じてスクリプトから取得します。public GameObject parcelPrefab;と宣言し、Inspectorでそのフィールドにプレハブをドラッグします。

Instantiate(prefab, position, rotation)はシーン内にプレハブのコピーを作成し、それを返します。この配送ドローンは、Spaceを押すたびに自身の位置に荷物を落とします。Quaternion.identityは回転なしを意味します。

public GameObject parcelPrefab;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Instantiate(parcelPrefab, transform.position, Quaternion.identity);
    }
}

押すたびに、HierarchyにParcel(Clone)という名前のオブジェクトが1つ追加されます。プレハブはそのままなので、コピーはすべて同じ値から始まります。ここではGetKeyDownが重要です。GetKeyを使うと、Spaceを0.5秒間押し続けた場合、1フレームにつき1つ、約30個の荷物を落としてしまいます。

challenge icon

チャレンジ

中級

クリックするたびに、プレイヤーの上にコインを出現させましょう。

  1. フィールド public GameObject coinPrefab; を追加します。シーンがCoinプレハブを割り当てます。
  2. Update() 内で、Input.GetMouseButtonDown(0) のときに、Instantiate(coinPrefab, transform.position + new Vector3(0, 2, 0), Quaternion.identity); を呼び出します。

「プレイ」を押し、移動してクリックします。クリックするたびにプレイヤーの上にコインが現れます。その後、「確認」を押します。

自分で試してみよう

using UnityEngine;

public class CoinDropper : MonoBehaviour
{
    public float speed = 4f;
    // coinPrefab: Coin prefabが設定されたpublicなGameObjectフィールド

    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
        }

        // Click: プレイヤーの2単位上にコインを生成する
    }
}

Unityスクリプトの基礎のすべてのレッスン

自分で練習してみよう: Unityプレイグラウンド