- Home /
How to choose base class to make Inherit C#
Hello everyone, I'm new on Unity and C#. In my project I need to choose the base class to make a child class inherit. In particular I have an Interface that defines all Character's methods:
public interface ICharacter
{
void Movement();
virtual void Attack();
virtual void Special();
void TakeDamage();
}
And I created two different classes that inherit MonoBehaviour and the interface ICharacter: the first one, "PlayerBehaviour", to Add to the Player in order to implement interface's methods and control the player gameObject, and "EnemyBehaviour", which controls AI's movement, attack, special power and Damage.
Every Character has a personal behaviour (for example character "Knight" has "KnightBehaviour"), in which i can override the special power and the attack method (for example use a sword or shoot an arrow), and where I assign values to the variables. This behaviour has to inherit from "PlayerBehaviour" or "EnemyBehaviour" according to whether when I instantiate the character prefab, and add his personal behaviour, i want it to be the player or a simple Enemy. I would not to create two scripts for every character, one for when it's the player and the other for when it's an AI.
is there a way to choose the class to make inherit?
public class PersonalCharacterBehaviour: myVariable
//where myVariable is PlayerBehaviour or EnemyBehaviour
{
...
}
for example I want to create a "Knight" as the player:
public class KnightBehaviour : myVariable {
...
}
//Where myVariable is PlayerBehaviour
and then I want to create a "Knight" as an AI:
public class KnightBehaviour : myVariable {
...
}
//Where myVariable is EnemyBehaviour
I don't know very well C#, i tried with Type.GetType and intanstiating new classes, but I can't find a valid solution. Thanks all.
Answer by AlbieMorrison · Sep 05, 2021 at 06:12 PM
One easy way might be to take the Character's personal behaviour script out of the gameobject, and write one "personal behaviour script" for each possibility (Knight Player, Knight AI, etc.) and have another script that runs instead, that just adds whichever script it needs to (using gameObject.AddComponent<yourScriptNameHere>();
) based on the instantiation.
Great! Does this answer work then? If it does you can accept it, if not I can help some more!
Answer by riki08_ · Sep 06, 2021 at 07:01 PM
@AlbieMorrison
Yes, it worked! Thank you very much. when I can I try to generalize the scripts as much as possible, but sometimes the easiest way is to create a few more. Thanks a lot, also for the quick answer ,Yes, it worked! Thank you very much. when I can I try to generalize the scripts as much as possible, but sometimes the easiest way is to create a few more. Thanks a lot, also for the quick answer