murelocal
murelocal

Reputation: 21

Monogame Object reference not set to an instance error

Guys need help in this problem a while. I code in visual C# express 2010 and monogame 2.5 to make game in windows, load some image using Texture2D for the game and compile. But when I try to compile the project it gives me this error. Object reference not set to an instance of an object.

    private static Game1 game;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        game = new Game1();
        game.Run();//This line gives the warning
    }
}

I try this code

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

but it didn't work, still it gives this error.

Object reference not set to an instance of an object

Did I miss something or should I install something to solve this?

Upvotes: 1

Views: 1448

Answers (2)

Kokodoko
Kokodoko

Reputation: 28128

In my version of Monogame a default project always starts out like this:

 static void Main()
        {
            using (var myGame = new Game1())
                myGame.Run();
        }

This seems to work.

Upvotes: 0

Andrew Russell
Andrew Russell

Reputation: 27245

From the information you've given, it sounds like the exception is being thrown from within MonoGame's Run method.

The first step in fixing this would be to get more information about the cause. The best way to do this would be to build MonoGame from source, along with your project, in the one solution. That way, when the exception is thrown, the debugger will break in the exact place within MonoGame the error occurs, and you can use the debugger to determine what the problem is.

The next-best thing - which you can do without needing the source - would be to view the details for the exception to get a stack trace. This will at least tell you what method is responsible for the exception. From there you can look it up in the source code and see if that provides any additional information.

(For this particular exception, "Object reference not set to an instance of an object", a stack trace is less helpful, as it gets thrown by the .NET framework (presumably due to a bug in MonoGame), rather than explicitly being thrown by MonoGame itself due to (for example) an error in API usage.)


If I had to guess the cause (and I do), I would guess that you're not setting up a GraphicsDeviceManager correctly in the constructor of your Game1 class (note how your constructor runs before Run). And, instead of detecting that situation and throwing an informative exception, MonoGame ploughs on until it crashes.

But this assumes that everything else is working normally. It could also be a problem with, for example, MonoGame not being able to initialise the graphics device for whatever reason. Or numerous other things, really...

(Another option might be to try and build your game against XNA, and see if what result that gives.)

Upvotes: 1

Related Questions