Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Composition vs inheritance (think Enemy)

Discussion in 'Scripting' started by codeBeast, Jul 23, 2021.

  1. codeBeast

    codeBeast

    Joined:
    Jun 8, 2013
    Posts:
    28
    I hope you don't get annoyed with this question. I understand the concepts as unity is mostly composition ie: components all put together on a game object BUT if you think about enemies, then do tendo to have many of the same characteristics in lots of games. Therefore, it is an OK design practise to use inheritance for enemies. They all attack, take damage, move around, fire stuff etc... So it makes sense to create a super class. I'm just asking.
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    That's a very dangerous trap to fall into:
    Saying "they all attack, take damage, move" is a very generous statement.
    You might have turrets or towers that won't move. You might have creatures that don't attack, but can be killed (think critters from starcraft). You might have threats that don't have health, but can attack the player.

    Composition over inheritance is not a unity exclusive thing. It's the preferred method in oop, for a reason too. Having these components depend on each other very lightly means you won't have to rewrite 10 components over and over, because one thing is slightly different.
    Of course you can always just have these systems as individual components with controls, then a more complex enemy ai component, that requires the previous components and orchestrates them accordingly.
     
    codeBeast likes this.
  3. jbnlwilliams1

    jbnlwilliams1

    Joined:
    May 21, 2019
    Posts:
    267
    Absolutely ok. And remember, one does not exclude the other. They can both be used.
     
  4. codeBeast

    codeBeast

    Joined:
    Jun 8, 2013
    Posts:
    28
    That's very interesting. With regards "controls" - I have no idea what they are. Have you got any links where I can read up on that "strategy".
     
  5. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    I mean public methods so that the ai component can interact with them. Basically an interface between them
     
  6. codeBeast

    codeBeast

    Joined:
    Jun 8, 2013
    Posts:
    28
    Maybe I need to post again but is there any chance of explaining how to use interfaces. I know what they are but I have no experience of using them. If not, no probs. Thanks for your help guys.
     
  7. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    I didn't specifically mean interface here as the actual coding term, rather just the fact, that you can interact with them somehow through their interface.