Game Development Community

Reading and writing a custom class properties from outside

by Arden · in Torque X 2D · 09/22/2010 (7:05 pm) · 4 replies

Hey guys, I have a somewhat rethoric question about classes.
I'd like to create a class that contains all of the game state stuff. For instance:

public class GameState
    {
        int _numberOfLivesRemaining = 3;
        int _score = 0;


        public int NumberOfLivesRemaining
        {
            get { return _numberOfLivesRemaining; }
            set { _numberOfLivesRemaining = value; }
        }

        public int playerScore
        {
            get { return _score; }
            set { _score = value; }
        }

        public int playerGold
        {
            get { return _score; }
            set { _score = value; }
        }

        public T2DSceneObject _currentSpawner
        {
            get { return _currentSpawner; }
            set { _currentSpawner = value; }
        }

My question is, once this class is saved and part of the solution as a CS file, how would I go about consulting its public properties and updating them from other components and methods?

I've tried using namespace.class.method syntax to no avail.

#1
09/22/2010 (7:14 pm)
In the new CS file give it a new namespace name

namespace NewNAME
{
    //Class code here
}

Now you should be able to call it with using

using NewName;

I have never tried this, but this is my understanding of how it works from viewing the source code of other files being used.

Let me know if it works!
#2
09/22/2010 (7:36 pm)
Ok so here's what I did:

- I changed the namespace for my Gamestate class to GlobalClass.
- I then added 'using' in my game.cs file.
- Then, to attempt to create a class instance I could use in my game.cs, I then added:

#region Private, protected, internal fields
        GameState _gameState;
then, in public void Startgame() I added:
_gameState = new GameState();

So far so good.
Finally I added to public properties:
public GameState GameStateCurrent
{
    get { return _gameState; }
}

I now have an object based on a class, but I'm still stomped as to how I manipulate it and look and update its properties. Since the object is now globally known as GameStateCurrent, I figure I should be doing something like:

GameStateCurrent.playerScore=100;

but that doesn't work, as I'm getting "A namespace does not directly contain members such as fields or methods"

... Any suggestions?

#3
09/22/2010 (8:22 pm)
Using the singleton method should work.

You'll want to call a method like this:
GameState.Instance.playerScore += 100;

Setting up a singleton for that class should look like this

public static GameState Instance
{
get
{
if (_instance == null)
_instance = new GameState();
return _instance;
}
}

private static GameState _instance;

The above code should be added to your GameState class.

#4
09/22/2010 (9:51 pm)
This is great Will. It works! This will be really useful!
My thanks :)