Unity 6 Play Modeテスト環境構築と実行方法

2026年11月9日

広告

Unity 6 の Play Mode テストで、落下したコインを回収したときにスコアが増えることを確認します。Unity Hub から Universal 3D プロジェクトを作成し、Window > General > Test Runner を開いてください。

テスト対象を参照できるようにする

Coin.cs と CoinCollector.cs を Assets/Scripts/CoinSample に置き、同じフォルダーに CoinSample.Runtime.asmdef を作ります。Test Runner の PlayMode タブでテストアセンブリ用フォルダーを作り、生成されたテスト用 .asmdef の Assembly Definition References に CoinSample.Runtime を追加して Apply を押します。 アセンブリ定義の詳しい手順

Coin.cs

using UnityEngine;

/// <summary>
/// コインであることを示すマーカーコンポーネント
/// </summary>
public class Coin : MonoBehaviour { }

CoinCollector.cs

using UnityEngine;

public class CoinCollector : MonoBehaviour
{
    [Tooltip("回収したコインの数")]
    public int score;

    private void OnTriggerEnter(Collider other)
    {
        // Coin マーカーを持つ相手なら回収
        if (other.GetComponent<Coin>() != null)
        {
            score++;
            other.gameObject.SetActive(false);
        }
    }
}

コインが回収されるまで待つ

回収役の Sphere をトリガーにし、その真上で Rigidbody 付きのコインを生成します。この例では床を省き、重力による落下と回収を検証します。回収が起きたフレームで待機を終え、3秒経過した場合はアサーションで失敗を報告します。

using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;

public class CoinCollectorTests
{
    [UnityTest]
    public IEnumerator DropCoin_TriggersCollection()
    {
        var player = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        GameObject coin = null;

        try
        {
            player.transform.position = new Vector3(0f, 100f, 0f);
            player.GetComponent<SphereCollider>().isTrigger = true;
            var collector = player.AddComponent<CoinCollector>();

            coin = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            coin.transform.position = player.transform.position + Vector3.up * 2f;
            coin.AddComponent<Coin>();
            coin.AddComponent<Rigidbody>();

            Assert.That(collector.score, Is.Zero);
            Assert.That(coin.activeSelf, Is.True);

            double deadline = Time.realtimeSinceStartupAsDouble + 3.0;
            while (collector.score == 0 && Time.realtimeSinceStartupAsDouble < deadline)
            {
                yield return null;
            }

            Assert.That(collector.score, Is.EqualTo(1),
                "制限時間内にコインを1枚回収するはずです。");
            Assert.That(coin.activeSelf, Is.False,
                "回収したコインは非アクティブになるはずです。");
        }
        finally
        {
            if (coin != null)
                Object.Destroy(coin);
            Object.Destroy(player);
        }
    }
}

Test Runner の PlayMode タブで DropCoin_TriggersCollection を選び、Run Selected を押します。テストでは「スコアが1増える」「コインが非アクティブになる」を別々に確認します。

Unity 6.6 Test Framework · OnTriggerEnter

訪問数 233 回, 今日の訪問数 1回

広告

Test,Unity

Posted by hidepon