- Home /
Getting the updated values of base class variables in Derived class
(Example problem stripped off all other junk to keep it simple)
Three game objects with their respective classes, A, BaseTest and InherTest(derived from BaseTest).
Class A, initializes a variable i to 5 in start() and after five seconds changes the value to 10.
I will then print the value of i in Update() of BaseTest() and in Update of InherTest()
public class A: MonoBehaviour
{
public BaseTest baseTest;
private void Start()
{
baseTest.I = 5;
StartCoroutine(incrementAfter());
}
IEnumerator incrementAfter()
{
yield return new WaitForSeconds(5);
baseTest.I = baseTest.I + 5;
}
}
public class InherTest : BaseTest
{
// Print value of i in Update()
}
public class BaseTest : MonoBehaviour
{
[SerializeField]
public int i;
public int I
{
get { return i; }
set
{
i = value;
}
}
}
Expected behavior and observed: Printing the value of i in BaseTest correctly shows i = 5 and then after five seconds, it shows i = 10.
What I didn't get: Printing value of i in Update() of InherTest always shows 0.
What I want: Latest value of i to be present in the derived class as well. Is it possible with this type of implementation? What needs to be changed? I do not think I have a firm grasp of inheritance. Please help me out.