Enemy detection build bug

So this is my current script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EndGame : MonoBehaviour {

    void OnGUI() {
        if (GameObject.FindWithTag ("Enemy") == null) {
            Debug.Log("Enemy not found");
           
            GUI.Label( new Rect(Screen.width/2 -50, Screen.height/2 -25, 100, 50), "Congratulations, you won! Restart the game!");
        }
    }
}

And it works when i play it in the editor, but when i build the game and run the executable. It just shows Congratulations, you won! Restart the game! continuously. It shouldn’t do that.

Please help!

Thanks!

That means there are no enemies in the scene with tag “Enemy”… maybe this code executes before you have spawned any enemies?

Also, instead of using OnGUI(), try using Update(),
ongui is called many times per frame, Unity - Scripting API: MonoBehaviour.OnGUI()

It works in the editor, so why shouldn’t it work in the build then?

And all the enemies have the “Enemy” tag.

Damm, i only tagged the enemies that are in the project window. Not the ones that are prefabs. Me dumb, don’t worry