Version: Unity 6.2 (6000.2)
Language : English
3. Moving character
5. Collision Test

4. Reach Wand Test

Learning Objectives

Perform Assertions on your character position and behavior.

Exercise

  1. Go back to the previous MovementTest.cs file.
  2. Write a MainScene\_CharacterReachesWand test that makes your character move right, and checks if it reaches the wand location.

Hints

  • Look for Altar and Sara Variant game objects in your sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
    See in Glossary
    . You are interested in measuring the X position of your Transform objects.
  • Wand location X position is equal float of 21.080. Main Character X position is dynamic and it changes whenever it moves.
  • Consider setting a timeout that makes the test fail if the Wand is not reached.

Solution

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

public class MovementTest
{
    private Transform _characterTransform;
    private float _testTimeout = 25.0f;
    private float _wandLocation = 21.080f;

    [UnityTest]
    public IEnumerator MainScene_CharacterReachesWand()
    {
      SceneManager.LoadScene("Assets/Scenes/Main.unity", LoadSceneMode.Single);
      yield return waitForSceneLoad();

      var elapsedTime = 0.0f;
      yield return GoRight();
      while (GetCurrentCharacterPosition() <= _wandLocation)
      {
          yield return null;
          elapsedTime += Time.deltaTime;
          if (elapsedTime > _testTimeout)
          {
            Assert.Fail($"Character did not reach location position in {_testTimeout} seconds.");
          }
      }
    }

    private float GetCurrentCharacterPosition()
    {
      // Get Main character's Transform which is used to manipulate position.
      if (_characterTransform == null)
      {
          _characterTransform = GameObject.Find("Sara Variant").transform;
      }

      return _characterTransform.position.x;
    }

    private IEnumerator GoRight()
    {
      TestInputControl.MoveLeft = false;
      yield return null;
      TestInputControl.MoveRight = true;
    }

    private IEnumerator waitForSceneLoad()
    {
        while (SceneManager.GetActiveScene().buildIndex > 0)
        {
            yield return null;
        }
    }
}
3. Moving character
5. Collision Test
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961