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

Inherit from custom class and MonoBehavior

Discussion in 'Scripting' started by jakejolli, Feb 16, 2015.

  1. jakejolli

    jakejolli

    Joined:
    Mar 22, 2014
    Posts:
    54
    I'm scripting in C#. I have a class StatsManager which contains methods and variables common between the player and the enemy. I have derived classes EnemyStats and PlayerStats which have some unique variables and behaviors.

    These scripts seem fine.

    However, I want to access the derived classes (EnemyStats and PlayerStats) using gameobject.getComponent(), but I apparently can't do this unless the script I'm trying to access derives from MonoBehavior (which, in hindsight, makes sense).

    Is there a way that I can achieve this using my current structure? i.e. is there something similar to the implements keyword in Java present in C#?

    If not, is there another way to do what I'm trying to do (use inheritance and OOD), or should I abandon what I've been taught formally (not that that's necessarily a bad thing) and just make scripts PlayerStats and EnemyStats, each containing both common and unique variables and methods and have them inherit from MonoBehavior?

    This would make some things easier, as I could treat PlayerStats as a singleton, but, in my opinion, will make my code less maintainable and more jumbled.

    I know I'm potentially opening a can of worms with this question, but what do you suggest as a solution?

    Thanks
     
  2. Dameon_

    Dameon_

    Joined:
    Apr 11, 2014
    Posts:
    542
    Have an abstract class, in this case let's call it Stats, amd have it inherit from MonoBehaviour. This class would contain your common variables. Then you make a PlayerStats class and an EnemyStats class that inherit from your Stats class. Voila!
     
  3. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    389
    What Dameon said, or add your Stat class as a field of a monobehaviour that already is on player / enemy
     
  4. jakejolli

    jakejolli

    Joined:
    Mar 22, 2014
    Posts:
    54
    Of course! Why didn't I think of that...

    Thank you!