Game Development Community

C# Question About Object References

by Randy Lutcavich · in Technical Issues · 09/15/2009 (3:06 am) · 2 replies

I'm working with TX2D and am unable to use variables declared in one class in a whole other class. How do I access a variable in another class in C#?

For example I declared a variable in my game class:
int _testInt;

Then I even create a public accessor:

But then I get an error when I try to access it in another class like this:
_playerScore.Text = Convert.ToString(Game.testInt);

Error:
" An object reference is required for the non-static field, method, or property 'StarterGame2D.Game.testInt.get' "

I don't get it. Shouldn't using "Game.testInt" work?

#1
09/17/2009 (8:32 pm)
I'm not a C# person by any means, but if it's anything like Java, the cause of your problem is probably the same. So I'm going to take a stab in the dark and say that your problem is that your variable is not static. (Hence the error about a "non-static field, method, or property".) If "Game" is the name of your class and not an instance of a class, you will probably need to make your "testInt" variable and accessor methods static. Otherwise, a "testInt" variable will be added to every instance of the Game class, and it won't be accessible from the global Game class itself.
#2
09/18/2009 (2:17 am)
The return type of Game is probably just the Microsoft.Xna.Framework.Game class, which does not have a "testInt" property. This is assuming you're running your code within a GameComponent.

Try this:

int x = ((MyGameClass)Game).testInt;