ImagineNation

I'm new to C#, I usually use VB.net and I'm having trouble finding how to access parent elements from inside objects.

For example, imagine I instantiate this object in my program: (Note the class is created in a separate text file from my main program)

namespace XNATest5
{
class Statistics
{
private int LastTime;
private int FrameCount;

public Statistics()
{
FrameCount = 0;
LastTime = Environment.TickCount;
}

public void Update()
{
FrameCount += 1;
if (Environment.TickCount - LastTime < 1000) return;
Window.Title = "FPS="+FrameCount.ToString(); <---- doesn't work
FrameCount = 0;
LastTime = Environment.TickCount;
}
}
}

It seems I can't refer to the "Window" variable from here, even though I know it exists. It doesn't matter if I qualify it with the full namespace (XNATest5.Game1.Window) it's not visible from here. Why is that In VB you can use the namespace to access actual instantiated objects during runtime.

Is there a way to do this in C# I know I can pass in "Game game1" as a variable in the constructor but it's a pain in the *** as then I would have to do it for a lot of my code and it seems unnecessary.

I can't even access public variables created in my main program; EG :

if I declare public int TestVar; and then create a statistics object in the same program, it cannot see TestVar, even though it is described as public!

Is there some export or import command i don;t know of or some other way to access variables that exist at runtime in parent scope







Re: XNA Game Studio Express How to you access parent elements from objects?>

dczraptor

You can access the public variables because they aren't static. You would need a reference to an instantiated Game class. However, you could try using static variables:

public MyGame : Game
{

public static int TestVar;
}

Then you can call it from anywhere by using Game.TestVar.

By the way, i think you should probably have a reference to your main Game class in almost every class you create. That way, you can access the game services, the game window (game.Window), the game components, etc.






Re: XNA Game Studio Express How to you access parent elements from objects?>

ImagineNation

Thanks for the info about static. Will consider using game object .... I guess as it's pass-by-reference it's not too much overhead ....maybe you're right...