プレイヤーがあるGameObjectに当たったら、別のGameObjectが出現(表示)されるものを作る方法を紹介します。
完成動作
BallがBlockに当たるとTriangleが出現します。
作り方
1.シーンに各オブジェクトを配置
1-1.以下のようにプレイヤーに見立てた赤いBall(Circle)と、青いBlock(Square)と白いTriangle(Triangle)を配置する。

2.赤いBall(Circle)の設定
2-1.Ballが落ちるように”Rigidbody 2D”をアタッチ


2-2.当たり判定を行うために”Circle Collider 2D”をアタッチ


2-3.Tagに”Payer”を設定

3.青いBlock(Square)の設定
3-1.当たり判定を行うために”Box Collider 2D”をアタッチ


3-2.DisplayTriangle.csという名前のスクリプトを作成して、以下のコードを記載する。
using UnityEngine;
public class DisplayTriangle : MonoBehaviour
{
[SerializeField]
[Tooltip("プレイヤーが当たったら表示したいGameObject")]
private GameObject displayTarget;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
// 当たったら表示したいGameObjectを非表示
displayTarget.SetActive(false);
}
private void OnCollisionEnter2D(Collision2D collision)
{
// 当たった相手のタグがPlayerかどうか判定
if (collision.gameObject.tag == "Player")
{
// プレイヤーに当たったら表示したいGameObjectを表示
displayTarget.SetActive(true);
}
}
}
3-3.作成したDisplayTriangle.csをSquareにアタッチ


3-4.”Display Target”プロパティにTriangleをアタッチ


完成
これでBallがBlockに当たるとTriangleが出現します。
コメント