Access child class variable inside child class script as a parent class of the parent script
Hello, I have a little class question, using C# language.
I have multiple vehicles, which have a script child of a general physics script:
public class Control : MonoBehaviour {
[...]
}
public class CarControl : Control {
[...]
}
public class TruckControl : Control {
[...]
}
What I wanted to achive is a similar thing for some physics parameters shared across the vehicles
public class VehiclePhysics {
public float engineTorque;
public float brakeTorque;
public float fuelTank;
public float currentFuel;
[...]
}
public class TruckPhysics : VehiclePhysics {
public float maxTrailAngle;
[...]
}
so to be able to have a VehiclePhysics type variable in the parent, but to be able also to pack inside it the specific values per vehicle
public class Control : MonoBehaviour {
public VehiclePhysics physics;
[...]
}
public class TruckControl : Control {
//here I should declare the "physics" variable of type "TruckPhysics";
[...]
}
The problem is I have no idea how to declare the class in the child script, so that if I access it as, let's say
void OnTriggerEnter (Collider other) {
other.GetComponent<Control>().physics.currentFuel += 50;
}
the currentFuel variable contained in the TruckPhysics class (child class of the VehiclePhysics) of TruckControl script (child class of Control script) should be set, and would work the same way with all the other vehicles.
Yes, I know I could store VehiclePhysics in a variable, and then create a per-vehicle variable containing the rest of the specific parameters, and have the physics split across those two classes, but I wondered if it would've been possible to solve this "problem" with a cleaner solution, like this one. Is it possible?
Thanks in advance :).
Your answer
![](https://koobas.hobune.stream/wayback/20220612101909im_/https://answers.unity.com/themes/thub/images/avi.jpg)