I created a simple unit test in unity where I simply try to use GameObject.FindGameObjectWithTag to check if a game object with the ‘Player’ tag is set, however even after using a custom tag, the test is failing to find any game object with that name.
This is my test code:
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
public class MainTest {
[Test]
public void MainTestSimplePasses() {
var player = GameObject.FindGameObjectWithTag("MyPlayer");
Assert.IsNotNull(player); // Fails!
}
// A UnityTest behaves like a coroutine in PlayMode
// and allows you to yield null to skip a frame in EditMode
[UnityTest]
public IEnumerator MainTestWithEnumeratorPasses() {
yield return null;
var player = GameObject.FindGameObjectWithTag("MyPlayer");
Assert.IsNotNull(player); // Also fails, even after skipping a frame!
// Use the Assert class to test conditions.
// yield to skip a frame
yield return null;
}
}
Yet when the game itself is run, the code seems to run just fine:
var player = GameObject.FindGameObjectWithTag("MyPlayer");
if (player == null)
{
// This never does get hit in play mode!
Debug.LogError($"{nameof(player)} is not initialized!");
}
What am I missing here? Why does the unit test fail to find any game object using this approach?