(UI Toolkit) "Destroy may not be called from edit mode" on game start

The game doesn’t crash at all, I’m just getting a red error message whenever I stop the game and press the IDE’s play button again.

The error says:

Destroy may not be called from edit mode! Use DestroyImmediate instead.
Destroying an object in edit mode destroys it permanently.
UnityEngine.UIElements.PanelSettings:OnDisable ()

The scene contains UIDocument with a C# script for controlling the UI.

public class MainMenuController : MonoBehaviour
{
    public Button multiplayerButton, trainingButton, accountButton, shopButton;

    void OnEnable ()
    {
        var root = GetComponent<UIDocument>().rootVisualElement;
        multiplayerButton = root.Q<Button>("multiplayer-button");
        trainingButton = root.Q<Button>("training-button");
        accountButton = root.Q<Button>("account-button");
        shopButton = root.Q<Button>("shop-button");

        multiplayerButton.clicked += MultiplayerPressed;
        trainingButton.clicked += TrainingPressed;
        accountButton.clicked += TrainingPressed;
        shopButton.clicked += ShopPressed;
    }

    void MultiplayerPressed() {
        Debug.Log("M");
    }

    void TrainingPressed() {
        Debug.Log("T");
    }

    void AccountPressed() {
        Debug.Log("A");
    }

    void ShopPressed() {
        Debug.Log("S");
    }
}

Hey, I have the same problem


I tried disabling my previous prefabed EventSystem in the scene, and the error does not appear after that.


Still don’t know the root cause of the problem but hope that it will help

I still get this error, I don’t have any other EventSystem in any scene.
Normally, the whole call stack is shown on errors, for some reason it is not displayed in my editor (?)

Destroy may not be called from edit mode! Use DestroyImmediate instead.
Destroying an object in edit mode destroys it permanently.
UnityEngine.UIElements.UIElementsRuntimeUtilityNative:UpdateRuntimePanels ()

Edit: Some more information: The error only appears in the editor, and does not seem to affect anything at all. I can also just follow it’s suggestion and change Destroy to DestroyImmediate, removing the error. Obviously I’d however rather not mess with immutable packages. The unity version is 2023.2.0b4.