Search Unity

I don't know if it's correct in unity C# inheritance.

Discussion in 'Scripting' started by CasualAttitude, Feb 13, 2020.

  1. CasualAttitude


    Feb 13, 2020
    Hi,I'm new in unity.
    There are some components used lots of times, and I don't want to pass them time by time
    So I'm wondering if I can inherit the script like this.

    Code (CSharp):
    2. //Player Controller
    3. public class Player : MonoBehaviour {
    4. {
    5. private void Update()
    6. {
    7. mover.Move(movement);
    8. }
    10. private void FixedUpdate()
    11. {
    12. movement = new Vector2(Input.GetAxis("Horizontal"), 0f);
    13. }
    14. }
    15. }

    Code (CSharp):
    2. //Play Movement
    3. public class Mover : Player {
    4. {
    5. public void Move(Vector2 movement)
    6. {
    7. // DoMove
    8. }
    10. }
    11. }
  2. _met44


    Jun 1, 2013

    You might want to go step by step with learning C#.

    As you may have noticed, unless you didn't put in there the whole code you have several errors that prevent from compiling.

    The Player.Update() method uses a "mover" variable that seems like composition, meaning a class referencing another.

    The declaration of the Mover class on the other hand, is inheritance.

    People often suggest composition over inheritance when making game code, i personnally think it depends what you're doing. In any case, it takes experience and lot of trials and lots of errors to begin to get clues about which is ideal.

    If you really want to go the inheritance road and Player is your base class, it should define a virtual Move() method that Mover can override. (i'll direct you to google to learn about keywords you might not know enough about in that sentence ;))
    CasualAttitude likes this.