![](/img/trans.png)
[英]How do you call a load content method in a class from another class (not main class) in xna
[英]In XNA, how do I modify something in the main game class from another class?
好的,默認情況下,XNA PC游戲的Game
類具有一個名為IsMouseVisible
的公共bool屬性,該屬性在設置時啟用/禁用鼠標可見。 我還有一個名為Configs
類,它監視被按下的特定鍵。 現在,我要設置它,以便當我按下特定鍵時,它將更改IsMouseVisible
的值。 這是我卡住的地方,因為我不知道如何從另一個類更改值。
我知道我可以在Configs
類中創建一個bool值,然后按一下該鍵,該值將更改,然后在主Game
類更新時,將IsMouseVisible
的值設置為Configs類的值,但事實是,我可能想創建多個不同的值(不僅僅是IsMouseVisible
),可以在另一個類的主Game
類中設置這些值。
我的問題是,我該如何在另一個主要課程的Game
類別中設置一些內容? (無需為我希望可訪問的每個值創建多個更新。)
在主類的構造函數中創建對象“ Configs”。 在執行此操作時,請為Config對象提供對主類的引用。 現在,Configs可以訪問主類的值。
您將需要將游戲類的引用傳遞給Configs類。 在Configs的類構造函數中,將私有成員變量設置為游戲類的實例。 從那里您可以操縱游戲。 見下文:
游戲類
public class Game1 : Game
{
Configs configs;
GraphicsDeviceManager _graphics;
SpriteBatch _spriteBatch;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// Pass THIS game instance to the Configs class constructor.
configs = new Configs(this);
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
}
}
配置類
public class Configs
{
// Reference to the main game class.
private Game _game;
public Configs(Game game)
{
// Store the game reference to a local variable.
_game = game;
}
public void SetMouseVisible()
{
// This is a reference to you main game class that was
// passed to the Configs class constructor.
_game.IsMouseVisible = true;
}
}
這基本上是其他人一直在說的。 但是,似乎您在不了解某些代碼的情況下很難理解這些概念。 因此,我提供了它。
希望能有所幫助。
三件事,它們都與您對@Patashu的答案的評論有關:
首先,如果要將Game
對象傳遞到構造函數中,則無需將其設置為ref類型參數,因為它是通過引用自動傳遞的(因為它是對象)。
其次,您的GameComponent
子類需要在其默認構造函數中引用Game
對象的原因……是因為它已經內置了對Game
的引用。 在您的Configs
類中,調用this.Game
這是主要的Game
實例。
第三,如果構造函數已經接收到一個對象的一個參數,則它不需要相同對象的同一實例的另一個參數。
閱讀文檔。 很有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.