Thursday, January 29, 2015

Having trouble calling variables

I think you are confused about what happens when one class inherits from another. HomeScreen inherits from KylesRpgGame, but this does not mean that an instance of HomeScreen will get all its data (or any data) from a completely different instance of KylesRpgGame.


So when you do this...



HomeScreen next = new HomeScreen();

...you get a new instance, which knows nothing about the instance of KylesRpgGame where it was created.


The usual way to deal with this kind of situation is to pass the instance of the first form to the second in the constructor. Something like so;



public partial class HomeScreen : Form // Just inherit from Form.
{
// Give the parent class scope, to make it easy to access anywhere in the class.
KylesRpgGame parent;

public HomeScreen(KylesRpgGame game)
{
InitializeComponent();

// Set the class-level variable.
parent = game;
MessageBox.Show(parent.Strength.ToString());
}
}


// In the first form, pass "this" to HomeScreen's constructor.

HomeScreen next = new HomeScreen(this);


No comments:

Post a Comment