- Home /
Is it possible to change value on base class when the same field gets changed on it's derived class
I'm using Unity here. My question is, is it possible to change value on base class when the same field gets changed on it's derived class? and vice-versa
I will give an example to make it clear:
public class BaseClass : MonoBehaviour{
public int x;
}
public class DerivedClass : BaseClass{
//-------------
}
public class AnotherClass : MonoBehaviour{
GameObject player = Instantiate(playerModel) as GameObject; //Assume playerModel is refrenced or something
DerivedClass example = player.GetComponent<DerivedClass>();
example.x = 5;
}
In this case player.GetCompenent<DerivedClass >().x
will print 5, but player.GetCompenent<BaseClass >().x
will print 0. Is there a way to have BaseClass X equal to 5? Without directly setting it to 5
Is it possible that you have more than 1 BaseClass (or a class that derives from it) attached to your player? Because what you have should work.
I do have 2 classes that inherit the BaseClass. Here I mentioned the DerivedClass. I do have another class that inherits the base class, but it's never used in the player GameObject
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Making a static class derive from MonoBehaviour in C# 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Inheritance Problems 1 Answer