当我将Texture2D作为参数传递给一个类时,这个纹理是空的

本文关键字:一个 纹理 Texture2D 参数传递 | 更新日期: 2023-09-27 17:52:48

下面是我遇到问题的代码:

namespace Menu_test
{
    /// <summary>
    /// The main menu screen is the first thing displayed when the game starts up.
    /// </summary>
    class MainMenuScreen : MenuScreen
    {
        #region Initialization
        ContentManager content;
        Texture2D playgame;
        Texture2D exit;
        /// <summary>
        /// Constructor fills in the menu contents.
        /// </summary>
        public MainMenuScreen()
            : base()
        {
            // Create our menu entries.
            MenuEntry playGameMenuEntry = new MenuEntry(playgame);
            MenuEntry exitMenuEntry = new MenuEntry(exit);
            // Hook up menu event handlers.
            playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
            exitMenuEntry.Selected += OnCancel;
            // Add entries to the menu.
            MenuEntries.Add(playGameMenuEntry);
            MenuEntries.Add(exitMenuEntry);
        }
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");
            Art.Load(content);
            playgame = Art.PlayGame;
            exit = Art.Exit;
            if (playgame==null)
                throw new ArgumentNullException();
        }

        /// <summary>
        /// Unloads graphics content for this screen.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
        }
        #endregion
        #region Handle Input

        /// <summary>
        /// Event handler for when the Play Game menu entry is selected.
        /// </summary>
        void PlayGameMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
                               new GameplayScreen());
        }

        /// <summary>
        /// Event handler for when the Options menu entry is selected.
        /// </summary>

        /// <summary>
        /// When the user cancels the main menu, ask if they want to exit the sample.
        /// </summary>
        protected override void OnCancel(PlayerIndex playerIndex)
        {
            ScreenManager.Game.Exit();
        }


        #endregion
    }
}

所以在MainMenuScreen()中,我的playgamenull,但在LoadContent()中,它不是null。基本上我想做的是传递一个Texture2D作为参数到MenuEntry类,但纹理是空的,甚至在被传递到类之前。如果你想运行它,你可以在这里下载完整的项目。

感谢您的阅读。

当我将Texture2D作为参数传递给一个类时,这个纹理是空的

LoadContent在您的MainMenuScreen初始化后由XNA调用。你可能不得不将playGame对象的使用推迟到纹理加载或初始化LoadContent中的MenuEntries。