Home > OS >  How to make the Script component of a GameObject inherit from its parent?
How to make the Script component of a GameObject inherit from its parent?

Time:08-28

I have a class with following public fields:

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: Building Class in Editor

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 ?

CodePudding user response:

Just as Unit inherits from MonoBehaviour, Building inherits Unit, which inherits MonoBehaviour. As such, you would ONLY add Building as a component to your GameObject. If you add both, you'll end up with two distinct components on your game object. Each component would have it's own set of variables, and listen and react to the Unity messages independently, for example Update() if it were present if both classes.

It's also interesting to note that MonoBehaviour inherits from Behaviour, which inherits from Component, which inherits from Object (UnityEngine.Object, not System.Object). So Building.cs in this case is just another subclass of a component and is treated as such. You can check out the lineage on the enter image description here

As you can see the building component has all fields of unit component. So yes it inherits everything. The building component is unit component all inside (start, update, CreateMover). If you add building component and unit component then you have 2 unit components where one of them is extended with start, update and CreateMover.

  • Related