Невозможно загрузить контент, если он не в основном игровом классе

public class Dirt : Tile
{
    Vector2 position;
    Texture2D texture;

    public Dirt(Game game, Vector2 Position)
        : base(game)
    {
        type = "dirt";
        textureName = "Textures/Dirt";

        position = Position;
    }

    public override void Initialize()
    {

        base.Initialize();
    }

    protected override void LoadContent()
    {
        texture = Salvage.contentManager.Load<Texture2D>("Textures/Dirt"); // This doesnt work

        base.LoadContent();
    }

    public override void Update(GameTime gameTime)
    {
        if (InputHandler.KeyDown(Keys.W))
        {
            position.Y -= 1;
        }
        else if (InputHandler.KeyDown(Keys.S))
        {
            position.Y += 1;
        }

        if (InputHandler.KeyDown(Keys.D))
        {
            position.X += 1;
        }
        else if (InputHandler.KeyDown(Keys.A))
        {
            position.X -= 1;
        }

        Camera.DesiredPosition = position;

        base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {
        Salvage.spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Camera.Transformation);
        Salvage.spriteBatch.Draw(texture, position, Color.White);
        Salvage.spriteBatch.End();


        base.Draw(gameTime);
    }
}

Загрузка работает нормально, если я загружаю ее в класс Salvage (класс основной игры).

Редактировать:

Ошибка, которую я получаю:

Salvage.spriteBatch.Draw(texture, position, Color.White); Этот метод не принимает null для этого параметра. Имя параметра: текстура

Вот код класса Salvage:

public class Salvage : Microsoft.Xna.Framework.Game
{

    public static GraphicsDeviceManager graphics;
    public static SpriteBatch spriteBatch;
    public static ContentManager contentManager;
    public static SpriteFont spriteFont;
    public GameStateManager stateManager;
    public Rectangle ScreenRectangle = new Rectangle(0, 0, 1024, 768);

    public Salvage()
    {
        graphics = new GraphicsDeviceManager(this);
        graphics.PreferredBackBufferHeight = ScreenRectangle.Height;
        graphics.PreferredBackBufferWidth = ScreenRectangle.Width;

        Content.RootDirectory = "Content";
        contentManager = Content;

    }

    protected override void Initialize()
    {

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        spriteFont = Content.Load<SpriteFont>("Fonts/DefaultSpriteFont"); // This works fine

        stateManager = new GameStateManager(this);
        GameplayState gameplayState = new GameplayState(this, stateManager);

        Components.Add(new InputHandler(this));
        Components.Add(new Camera(this, ScreenRectangle));
        Components.Add(stateManager);

        stateManager.ChangeState(gameplayState);

    }


    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || InputHandler.KeyReleased(Keys.Escape))
            this.Exit();

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        base.Draw(gameTime);
    }
}

И код для плитки

public abstract class Tile : Microsoft.Xna.Framework.DrawableGameComponent
{
    public string textureName;
    public string type;

    public Tile(Game game)
        : base(game)
    {

    }

    public override void Initialize()
    {

        base.Initialize();
    }

    protected override void LoadContent()
    {

        base.LoadContent();
    }

    public override void Update(GameTime gameTime)
    {

        base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {

        base.Draw(gameTime);
    }
}

Редактировать:

Вот класс GamePlayState

public class GameplayState : GameState
{

    public GameplayState(Game game, GameStateManager manager)
        : base(game, manager)
    {
        childGameComponents.Add(new Dirt(game, new Vector2(0, 0)));
    }

    public override void Initialize()
    {

        base.Initialize();
    }

    protected override void LoadContent()
    {
        base.LoadContent();
    }

    public override void Update(GameTime gameTime)
    {

        base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {

        base.Draw(gameTime);
    }
}

person Diddykonga    schedule 02.06.2011    source источник
comment
Не хватает информации. Какую ошибку вы получаете? Можете ли вы предоставить соответствующий код для классов Salvage и Tile?   -  person Andrew Russell    schedule 02.06.2011
comment
Я думаю, что ошибка в классе GameState. Откуда это?   -  person Andrew Russell    schedule 04.06.2011


Ответы (1)


Я видел твою проблему. Вы объявляете переменную contentManager, но никогда не назначаете ее до метода LoadContent. Если вы загружаете Dirt до этого, у вас не будет допустимой переменной ContentManager, что приведет к сбою.

В конструкторе класса Salvage добавьте следующую строку:

contentManager = Content;

Это должно решить вашу проблему.

person Neil Knight    schedule 02.06.2011
comment
Я все еще получаю ту же ошибку, потому что я не создавал Dirt Tile, пока не был создан класс gameState. - person Diddykonga; 02.06.2011
comment
@DiddyKonga: Можете ли вы указать, какой класс создается первым, чтобы я мог лучше понять, что происходит? - person Neil Knight; 02.06.2011
comment
K хорошо, цепочка примерно такая: Salvage(Main Class) создает GamePlayState, затем GamePlayState создает Dirt Tile. - person Diddykonga; 02.06.2011