Question

I'm trying to use a variable that is declared in Game1.cs, in another class.

To simplify things, I created a new project, and want to manipulate the int variable x. I get Object reference not set to an instance of an object. at game.x = 0;

I'm new to C#, anyone can tell me what the problem is, and how to fix it?

This is the class:

class Class1
{
    Game1 game;

    public void init()
    {
        game = new Game1();
    }

    public void Update()
    {
        game.x = 0;
        game.x++;
    }
}

This is my code in Game1.cs

public int x = 0;
Class1 y = new Class1();
    //other stuff
protected override void Initialize()
        {
            y.init();
            base.Initialize();
        }
// Other stuff...
        protected override void Update(GameTime gameTime)
        {
            y.Update();
            base.Update(gameTime);
        }
Was it helpful?

Solution

I'd suggest doing some programming tutorials. There is almost never a good reason to manipulate a public field this way. Then too, there's a naming issue. What is x? The horizontal position of the entire window? Some object? Something else entirely? Be as obvious as possible, and it will go well for you.

The actual problem is likely that game is null in update, which seems rather odd. If you REALLY want to do this, I'd suggest modifying Class1.Update to Class1.Update(Game1 game). Then you can do y.Update(this).

Still, this is definitely the wrong way to solve the problem. You can do it better. Just be aware of that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top