- Home /
How to manipulate variable in base class?
I'm trying to make a 3D traffic game and I'm a complete newbie to Unity and C# so I'm having some trouble changing variables. So I have the following base class for my car object
public class car : MonoBehaviour
{
protected int roadID;
public virtual int GetroadID()
{
return roadID;
}
}
all of the other scripts associated with the car derive from this class. If I wanted to change the roadID of the car using another script associated with car, how would I do that? I have tried changing the value by creating a function that assigns the value and then assigning it as such:
this.roadID=DetermineID();
but it doesn't change the value, it remains zero even if I make the function return 1 so the problem isn't the function itself. I have also tried calling a function inside the base class but that doesn't work either. The roadID variable is the index of the road that the car is on, so it changes. As such, I have tried to assign it in Update. How do I use a function to change a base class variable's value?
Answer by Ermiq · Jan 22, 2020 at 04:35 PM
You have declared the roadID
as protected
. And since any class that is derived from a base class have full access to any protected
field of the base class, you shouldn't have any problems here. For example, you have a class Taxi
which is a derivative of the Car
class (notice, class names are with capital letters, it's a common standard in C# (and almost any other language as well)):
public class Car : Monobehaviour {
protected int roadID;
public virtual int GetRoadID {
return roadID;
}
}
public class Taxi : Car {
void Start() {
roadID = 5;
}
}
I'm pretty sure that your problem is: you have both Car
and Taxi
scripts attached to the object. That's why you have roadID
value 0
. The thing is the Taxi
script alone already have a Car
script 'built-in`, since you declare a class as derived from another class, the compilator automatically adds all base class fields, properties and methods to the derived class.
And when you have both Taxi
and Car
scripts attached, you actually have 2 Car
instances on the object: one from the base class and one from the derived class. And when you change the roadID
in the derived class you change it in the instance that is built-in in the derived class, while the other base class instance (the separate Car
script on the object) has its own roadID
which is not affected by Taxi
manipulations.