Search Unity

How to allow a class to accept all derived classes of another class?

Discussion in 'Scripting' started by Cavlon, Jun 8, 2021.

  1. Cavlon

    Cavlon

    Joined:
    Jan 15, 2020
    Posts:
    3
    I am making an enemy script which uses a state machine based on classes, I have made a State class which all the different states are derived from and each of these classes require an EnemyController class for its variables and methods. I have also made 3 different enemy classes which derive from the EnemyController class but these cannot be input into the states. I also cannot input any public or [Serializable Field] variables into the three enemy classes from the inspector.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    I think you may have confused yourself with too much going on at once.

    I know you have successfully confused me at least with your description of it.

    For instance, how is an enemy also a state?

    Perhaps you can explain what you're actually trying to do?
     
  3. Cavlon

    Cavlon

    Joined:
    Jan 15, 2020
    Posts:
    3
    Sorry for the confusing description, the enemy classes are not a part of the state classes, they derive from the EnemyController which is separate from the states. For my states to work, it takes a parameter of EnemyController:

    Code (CSharp):
    1. public State(EnemyController enemy)
    2.     {
    3.         this.enemy = enemy;
    4.     }
    However, instead of it taking EnemyController, I want it to take either EnemyControllerA, EnemyControllerB or EnemyControllerC and work the same for each of them with each controller being slightly different for each enemy.
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    If EnemyControllerA, EnemyControllerB, and EnemyControllerC are derived from EnemyController (and they should be), then you can pass them in as the parameter.
    Code (csharp):
    1. public class EnemyControllerA : EnemyController {
    2.  
    3. ...
    4. ...
    5.  
    6. EnemyControllerA eca = gameObject.GetComponent<EnemyControllerA>();
    7. State stateA = new State(eca); //works fine with your constructor from your comment above
     
  5. Cavlon

    Cavlon

    Joined:
    Jan 15, 2020
    Posts:
    3
    Thanks, it turns out this aspect of my code worked the entire time but the error was due to a state having variables that are not present in the main EnemyController but are in EnemyControllerA.