我正在使用 enum
在主菜单上使用,但我遇到了一个错误,我已经查看了一段时间,但找不到问题所在。
我正在做的是为菜单的每一页我有一个类保存图像和矩形。当鼠标悬停在图像上并单击时,会将字符串更改为名称以使程序执行某些操作。
问题
由于某些原因,当我的 TitleScreen.cs
更新时,字符串 mouseOn
不会从 "None"
更改。怎么了?
标题屏幕类:
public class TitleScreen
{
Game1 game1;
public void Initialize()
{
game1 = new Game1();
}
public void Update(GameTime gameTime)
{
MouseState mouse = Mouse.GetState();
if (mouse.LeftButton == ButtonState.Pressed && game1.mouseUsed == false && game1.mouseActive == true)
{
if (play.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Play";
game1.mouseUsed = true;
}
else if (title.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Title";
game1.mouseUsed = true;
}
else if (options.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Options";
game1.mouseUsed = true;
}
else if (quit.Contains(mouse.X, mouse.Y))
{
game1.mouseOn = "Quit";
game1.mouseUsed = true;
}
}
}
在主类中:
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
images = new Images();
startup = new StartUp();
resolution = new Resolution(new Vector2(screenWidth, screenHeight));
options = new Options();
credits = new Credits();
titlescreen = new TitleScreen();
images.Content = Content;
graphics.PreferredBackBufferHeight = (int)resolution.screenResolution.Y;
graphics.PreferredBackBufferWidth = (int)resolution.screenResolution.X;
graphics.ApplyChanges();
}
protected override void Initialize()
{
titlescreen.Initialize();
base.Initialize();
}
最佳答案
您正在 TitleScreen 类中创建另一个 Game 对象。我不确定为什么你需要在标题屏幕中引用完整的 Game 类,如果它只是用于输入命令,你通常最好创建一个单独的输入类并引用它。不管怎样,如果你想正确引用 Game1 而不是新的,你需要这样做:
public class TitleScreen
{
Game1 game1;
public void Initialize(Game game1) //Or (Game1 game1) both work since Game1 is a child from Game.
{
this.game1 = new Game1();
}
}
现在,当您在 TitleScreen 对象上调用 Initialize 方法时,您使用 this
将 Game1 对象传递给它。
protected override void Initialize()
{
titlescreen.Initialize(this);
base.Initialize();
}
如果您实际上正在检查 Game1 类中的输入,则不会将其传递给 TitleScreen。解决此问题的最简单方法是按照我们上面所做的相同方式在您的更新方法中传递 Game1。
public void Update(GameTime gameTime, Game1 game1)
{
this.game1 = game1;
MouseState mouse = Mouse.GetState();
}
同样,您需要在 Game1 更新方法中传递每个更新循环:
titleScreen.Update(gameTime, this);
我不能保证这会奏效,您可能只需要一个更好的架构(恕我直言,只传递完整的 Game1 对象并不是一个好主意)。当我需要 Game1 中的特定内容时,我只是为它创建属性并引用它。我确实希望事情能为您弄清楚一点,这很像您正在传递 GameTime 和 SpriteBatch,如果您已经传递了整个 Game1 对象,则不需要传递它们。
关于c# - 引用类和字符串使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22561367/