Update base class variable value to pass it between subclasses already attached to game objects

I have a class which will have methods for subclasses and variables to pass values between them.
Classes PhaseOne and PhaseTwo are already attached to game objects at the same time, when Val is 0, at least I think this goes like this. And that is why value is not updated in the second class. Question is how to update ? Some kind of “reinheritance” from parent/base class ?

public class TestClass : MonoBehaviour {

	public int Val { get; set; }

public class PhaseOne : TestClass, IState {

	public void Enter ()
		print(Val); // 0
		Val = 15;
public class PhaseTwo : TestClass, IState {

	public void Enter ()
		print(Val); // still 0

I’m not understanding what the issue is. Could you explain it a bit more please? What is the goal of this? What are you trying to achieve with these classes? If you could describe step by step what you’re doing and what exactly isn’t working as you’d expect, it’ll be a lot easier to help you.


Why would it? Instances of PhaseTwo don’t know that instances of PhaseOne exist, neither group cares what the other does with its members. No instances of those share any values with instances of the other.

You might be confused about how inheritance works. In the above declarations, all PhaseOne and PhaseTwo inherit from TestClass is an integer called Val. And that’s it. There’s no special version of Val that knows what happens across instances of those other two classes, nor is there a special secret instance of the base TestClass preserving values to share across other derivatives.

The issue I can see is this:

The problem is when I change Val in PhaseOne Class, PhaseTwo prints out value not changed ( 0 ). What I think is because they are already added to gameObject before Val changed.

You are expecting that, when an instance of PhaseOne modifies its Val, the instance of PhaseTwo will automatically reflect this change on its own Val property. PhaseOne and PhaseTwo objects are separate instances and each of them have their own Val property, they are not linked in any way, even if they share a parent class. Inheritance is for code reusing , it doesn’t mean that child classes will implicitly share values in any way.

With that being clarified, there’s still the problem of sharing the data. IMO your best option here is to have the class that manages all of these Phase classes, pass them the correct data when needed, this could be done with events, or plain delegates, of you could simply structure the system in a way that every Phase contains the correct data before running their methods.

Hope this helps!

thanks to both of you for you explanation. You’re right. I’m new into inheritance and oop stuff. This helps to understand. I will go with manager class and helper class with added objects in the inspector.