[英]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.