Can I access the game variable used in Program.cs? (MonoGame)

时间:2015-07-28 23:51:10

标签: c# variables local monogame

I am making a game using MonoGame and C#. The main class is called Program.cs and is automatically added when creating the project. It uses these lines of code to run the game:

<xs:import namespace="http://ws.myproject.priv.schema/MyServiceA/v1" schemaLocation="xsd/myServiceA_v1.0.xsd"/>

The Game1 class contains properties that I need to use in other classes, but the only way to access them at the moment is by making the properties static and using code like the following:

using (var game = new Game1())
    game.Run();

I'm sure that this is bad programming practice, so I was wondering if there was any way for me to access the "game" instance variable from Program.cs so that I don't need to use static properties. However, the "game" instance is a local variable. Is there any way at all for me to call it using a manner like the following:

int exampleNumber = Game1.MyNumberProperty;

Edit:

I've created an example class to hold some of the variables and have instantiated it in the Game1 constructor.

int exampleNumber = Program.game.MyNumberProperty;

However, I am confused as to how I can now access this instance in another class. The way that I am doing it now is to make the instance static and use a static property, but now I'm back to the original problem.

1 个答案:

答案 0 :(得分:1)

将你的变量放在特定的类中,这些东西比游戏更好地描述它们。例如,一个Settings类,这样你实际上会要求存储在游戏类中的Settings对象,它为你的依赖项提供了更多的上下文。

现在,要修复您必须为Settings类创建的静态属性,您有两种方法:

1:在游戏类的启动时手动实例化所有对象,基本上你将自己连接所有依赖项。

2:使用像Unity这样的依赖注入框架。