public class Unit : MonoBehaviour
{
public int maxHealth;
public int health;
public bool isSelected = false;
public bool canMove = false;
public bool canCreateUnits = false;
public bool canAttack = false;
public bool canGatherResources = false;
}
And then a subclass which has a method that can be triggered if the field isSelected is TRUE:
public class Building : Unit
{
void Start()
{
canCreateUnits = true;
maxHealth = 1000;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.B) && this.isSelected)
{
CreateMover();
}
}
void CreateMover()
{
// behaviour here
}
}
In the unity editor, I have a prefab which corresponds to the Building subClass:
If I add as a component the script Building.cs to the GameObject Building, does it inherit everything from Unit.cs ?
Or does it need to have the Unit script as a component too ?
Please use code tags to post code. Makes it easier readable. But yes, since your Building is a Unit, it inherits all the fields from Unit, as you can see in your own screenshot, where both have the maxHealth, despite it only being defined in Unit. So a Building is always also a Unit. However, as @RadRedPanda said, the two are different components. If you put both on the same gameobject, they wont interact in any way unless you tell them to. Since i’m not entirely sure what the actual core of this question is, let me just clarify that you could have isSelected = False for the Unit component on that gameobject, while having isSelected = True for the Building component on the same gameobject, if you put both on it. The same would be true if you, for some reason, added two Building or two Unit components to the same gameobject however, so this has nothing to do with inheritance.
If this does not answer your question, please clarify what the you actually mean.
@Yoreki Thanks for explaining this, other parts of my code expected the Unit Script Component specifically to work (only some type of units can be selected) which made me doubt if I could only pass Building, but that is another question !
It indeed messed up the isSelected field, as it was added only to Unit and not Building.
So the correct implementation is deffinitely to add only Building, and then make that other part of the code check if the GameObject is of class Unit to be able to be selected.
Thanks again !
Things that expect a Unit will run when given a Building, since a Building is a Unit. If you have a Building component and check its type (is, typeof, …) and compare it to a Unit, it will return True aswell. Im pretty sure Unitys GetComponent would also return a Building component (as a Unit tho), if it finds one.