2012-02-09 31 views
0

我試圖在列表中存儲一系列GameObjects。由於某種原因,任何時候我把一個對象放在列表中,它就會失去它的精靈引用(變爲null)。所有其他對象數據(位置,顏色等)似乎都停留在對象中。這是我一直在嘗試:放置在列表中時玩家對象會丟失紋理

static class Global 
{ 
     public static List<GameObject> objects = new List<GameObject>(); 
} 

這是我正在使用的列表。現在有問題的對象 - 玩家:

class Player : GameObject 
{ 
    public Vector2 position = Vector2.Zero; 
    public Texture2D sprite; 
    public Color image_blend = Color.White; 

    public Player() : base() 
    { 
     //nothing here, nothing in base class either 
    } 

    public void Draw(SpriteBatch spriteBatch) 
    { 
     spriteBatch.Draw(sprite, position, image_blend); 
    } 
} 

最後,在我的主要XNA類(重要片段):

protected override void LoadContent() 
    { 
     spriteBatch = new SpriteBatch(GraphicsDevice); 
     sprPlayer = Content.Load<Texture2D>("player"); 

     player = new Player(); 
     player.sprite = sprPlayer; 
     Global.objects.Add(player); 
    } 

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

     spriteBatch.Begin(); 
     for (int i = 0; i < Global.objects.Count; i++) 
     { 
      Global.objects[i].Draw(spriteBatch); 

     } 
     spriteBatch.End(); 

     base.Draw(gameTime); 
    } 

我有一種感覺,我可能要對這個錯誤的方式。任何幫助表示讚賞。

回答

0

球員有一個名爲「精靈」不是你的遊戲對象類的Texture2D成員(你沒有張貼的代碼)。

所以,當你創建Player類,您分配它的成員的Texture2D,那麼您存儲Player作爲它的父遊戲物體使得它的所有特定對象類型承包商,客人無法訪問。

要解決,你想使你的遊戲對象基地有成員「精靈」並沒有在這是一個從遊戲對象繼承您的播放器類。

+0

我想我發現了這個問題。我沒有在'GameObject'中聲明'Draw'和'Update'方法爲'virtual',所以它們沒有被Player類正確覆蓋。謝謝你的幫助! – 2012-02-09 05:39:56

0

你的列表objectsGameObject列表。我在猜測你的player對象中的任何數據都不是GameObject類的一部分,因此將被拋出。我不知道,但..

而且,你真的應該對你的精靈的紋理不同的方法。當你決定添加一堆玩家和敵人的實體時,其中的每一個實體都會有自己獨立的紋理。如果你決定添加100個這樣的傢伙,你會有100個相同紋理的副本。

首先,我會建議加載紋理到紋理數組。

//Please excuse my bugs, I haven't used c# in a while 
//Place this in your global class: 
public static Texture2D[] myTextures = new Texture2D[1]; //or more if you decide to load more. 
//And place this in your LoadContent() Method: 
Global.myTextures[0] = Content.Load<Texture2D>("player"); 
//Also, modify your player class: 
public int textureIndex = 0; 

public void Draw(SpriteBatch spriteBatch) 
{ 
    spriteBatch.Draw(Global.myTextures[textureIndex], position, image_blend); 
} 

現在,而不是每個玩家對象擁有自己獨立的紋理,它使用數組中的紋理。現在你可以有很多實體沒有不必要的重複紋理每個實體

+0

感謝您的幫助。事實證明'GameObject'類需要它的函數聲明爲'virtual',以便它們被'Player'類正確覆蓋。儘管如此,我一定會使用你的方法來製作紋理。我不知道他們會被每個對象複製。 – 2012-02-09 05:42:18

+0

它們不會被每個對象複製 - Content.Load ()總是返回相同的對象實例,而不是每次調用時的新副本。請參閱MSDN中ContenManager.Load()的定義http://msdn.microsoft.com/zh-cn/library/bb197848.aspx – hatboyzero 2012-02-09 20:19:11

相關問題