0

我什至应该使用访问器吗?如果没有,我该怎么做?

我正在尝试在我的游戏中加载纹理LoadContent(),然后尝试将其传递给,Update()以便我可以在另一个类中将其用于碰撞检测目的。

这是我的代码:

游戏1.cs

public class GetTileType
{
    public Texture2D dirt;
    public Texture2D Dirt
    {
        get
        {
            return dirt;
        }

        set
        {
            dirt = value;
        }
    }
}

public class Main : Game
{
GetTileType getTileType = new GetTileType();

protected override void LoadContent()
{

    getTileType.Dirt = Content.Load<Texture2D>("Dirt");
}

protected override void Update(GameTime gameTime)
{
    Texture2D dirt = getTileType.Dirt;

    player.GetTileType(dirt);

    base.Update(gameTime);
}

Player.cs(暂时保存碰撞信息)

public void GetTileType(Texture2D groundTexture)
{
    Tile tile = (Tile)Main.currentLevel.GetTile(0, 0);

    Texture2D texture = tile.Texture;

    if (texture == groundTexture)
    {
        // Write code to handle what to do if the player tries to enter the ground.
    }
}
}

中还有更多内容LoadContent(),但与此问题无关。对Update(). 在调试中,player.GetTileType(dirt);显示为 null。如果我没记错的话,它应该是“污垢”。

我觉得我做这一切都错了,但我想不出任何其他方法来做到这一点。我尝试过的其他一切都变成了死胡同。

当我开始游戏时,它会加载,然后就挂起。然后我必须从任务管理器中停止它。

谁能告诉我我做错了什么?非常感谢。

4

1 回答 1

0

您的代码中的问题是您总是在创建新的GetTileType.

LoadContent您创建一个实例时 - 我们称之为 A - 并Dirt在该实例上设置属性。
但是您不会将该实例保存在任何地方,在方法完成后, A 超出范围并最终将被垃圾收集。

Update您创建一个新实例 - B - 并从中检索Dirt属性的值。
因为这是一个新创建的实例,所以这是null.

于 2012-12-13T11:10:08.980 回答