簡體   English   中英

如何使用訪問器設置此變量?

[英]How do I use accessors to set this variable?

我是否應該使用訪問器? 如果沒有,我該怎么辦?

我試圖在我的游戲中的LoadContent()下加載一個紋理,然后嘗試將其傳遞到Update()以便在另一個類中將其用於碰撞檢測。

這是我的代碼:

Game1.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); 出現為空。 如果我沒記錯的話,應該是“ Dirt”。

我覺得我要把這一切都弄錯了,但是我想不出任何其他方法來做到這一點。 我嘗試過的其他一切都變成了死胡同。

當我開始游戲時,它會加載,然后掛起。 我必須從任務管理器中停止它。

誰能告訴我我在做什么錯? 非常感謝你。

代碼中的問題是,您始終在創建GetTileType新實例。

LoadContent您將創建一個實例-我們將其稱為A-並在該實例上設置Dirt屬性。
但是您不會在任何地方保存該實例,方法完成后,A超出范圍,最終將被垃圾回收。

Update您將創建一個新實例B-並從中檢索Dirt屬性的值。
由於這是一個新創建的實例,因此為null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM