条件によって、どのPrefabを生成するか、変更できる仕組みを作りましょう。
今回の例では、3種類のSphereを用意。
Cubeに触れると、順繰りで次のSphereが出現しますが、下に落ちて通過するとそのままのSphereが出現します。

触れると次のPrefabが出現
Sphere1~3を作成し、リジッドボディを追加。
Ballという名前のタグを付けます。

Sphere1~3をプレハブ化します。

Sphere1~3の元データは削除しておきます。

続いて、ボールを生成する場所として、空のオブジェクトを作成します。
BallSpawn.csを作成し、GameObject(空のオブジェクト)に追加します。

BallSpawn.csを記述します。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallSpawn : MonoBehaviour { public static BallSpawn instance; public GameObject[] prefabArray; public void Awake() { if(instance == null) { instance = this; } } void Start() { Instantiate(prefabArray[CubeScript.instance.count], new Vector3(0, 3.0f, 0), Quaternion.identity); } public void Generate() { if(CubeScript.instance.count < 3) { Instantiate(prefabArray[CubeScript.instance.count], new Vector3(0, 3.0f, 0), Quaternion.identity); } } } |
prefabArrayのサイズを3と入力し、3種類のSphereを入れます。

続いて、ぶつける相手オブジェクトを作成しましょう。
Cubeを作成し、下のほうに配置。
今回は当たり判定にTriggerを使用するため、「トリガーにする」にチェックを入れます。
CubeScript.csを作成し、Cubeに追加します。

CubeScript.csを記述します。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CubeScript : MonoBehaviour { public static CubeScript instance; public int count; public void Awake() { if(instance == null) { instance = this; } } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Ball")) { Destroy(other.gameObject); count++; BallSpawn.instance.Generate(); } } void Update() { if (Input.GetKey(KeyCode.LeftArrow)) { transform.Translate(-0.1f, 0f, 0f); } if (Input.GetKey(KeyCode.RightArrow)) { transform.Translate(0.1f, 0f, 0f); } } } |
次に、Prefabが通過したときの当たり判定をつくります。
空のオブジェクトを作成。
名前を、BottomAreaに変更します。

BottomAreaにボックスコライダーを追加し、サイズと位置を変更します。

Cubeの下に配置しています。

BottomScript.csを作成し、BottomAreaに追加します。

BottomScript.csを記述します。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; public class BottomScript : MonoBehaviour { void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Ball")) { Destroy(other.gameObject); BallSpawn.instance.Generate(); } } } |
ゲームプレイしてみましょう。
PrefabがCubeに触れると、次のPrefabが出現。
Prefabがぶつからずに通過すれば、そのままのPrefabが出現します。
