![](/img/trans.png)
[英]In XNA, how do I modify something in the main game class from another class?
[英]How do you call a load content method in a class from another class (not main class) in xna
我正在為學校制作一款游戲,里面有3個迷你游戲,我想將迷你游戲分成自己的班級,這樣主班級不會變得太擁擠和難以閱讀,但是每次我嘗試運行說的游戲
"An unhandled exception of type 'System.NullReferenceException' occurred in Summer Assignment.exe"
當我取出從類中加載內容的行並且我以前使用過類時,游戲運行正常,所以這里的問題不是代碼
class Quiz
{
QuizQuestion no1;
ContentManager theContentManager;
SpriteBatch thespriteBatch;
int question = 0;
public void initialize()
{
no1 = new QuizQuestion();
}
public void LoadContent()
{
no1.LoadContent(this.theContentManager);
}
在我要從load content方法加載內容的類中是
public void LoadContent(ContentManager theContentManager)
{
font = theContentManager.Load<SpriteFont>("Font2");
}
該類已在主游戲類中正確加載,在添加下一個類之前,我先運行了該類,以確保
您需要為您的字段分配實際對象。 如果查看Quiz.theContentManager
,您會發現實際上從未為它分配值。 您可以通過從Game1
傳入來解決此問題。 例如,Game1應該如下所示:
public class Game1 : Microsoft.Xna.Framework.Game
{
Quiz quiz;
protected override void LoadContent()
{
quiz.LoadContent(Content);
}
protected override void Update(GameTime gameTime)
{
quiz.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
quiz.Draw(spriteBatch, gameTime);
}
}
然后,您的Quiz類應如下所示(請注意,使用這種方法,不需要任何XNA內容的類字段):
public class Quiz
{
QuizQuestion no1 = new QuizQuestion();
public void LoadContent(ContentManager content)
{
no1.LoadContent(content);
}
public void Update(GameTime gameTime)
{
// Perform whatever updates are required.
}
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
// Draw whatever
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.