I’m new to OOP and still crawling to understand the usage of “Class Inheritance Vs Implementation of Interface”. Please bear with me.
I’ve seen similar question being asked but i can’t make the essence out of it. Here’s what i’m trying to do:
I have a base class named “Projectile” (i’m in doubt whether to inherit from MonoBehaviour or not).
The child class name “Egg” inherit from projectile class.
public class Projectile : MonoBehaviour{
string _name; //name of projectile
int baseSpeed; //raw speed
//Default Constructor
public Projectile() { }
//2nd Constructor
public Projectile(string name, int _baseSpeed)
{
_name = name;
baseSpeed = _baseSpeed;
}
////////////////////////////////////////////////////////////////////////////////////
public class Egg : Projectile {
//Egg constructor, using base's 2nd Constructor
public Egg() : base("Egg", 1)
{
}
void Start()
{
Egg egg = new Egg();
}
I got some warnings and errors for doing just this.
- I can’t instantiate Egg because the base class inherit from MonoBehaviour (problem with using ‘new’ on MonoBehaviour). Some solutions said omitting the base class inheritance from MonoBehaviour and adding the script to a gameObject. How can i attach a script that is not a derivative of MonoBehaviour? maybe i misunderstand some point here.
- I don’t see any necessity to attach Projectile script. I only need it as a base class. I need the child class “Egg” to be attach to an egg gameobject on the scene. But it seems i have to attach Projectile to some empty gameobject to run the script. Is there any workaround for this?
- OOP matter wise. what considered good practice on communication between classes? should i just inherit all the way, or implementing interface?
Thank you for the time spent on reading all of this.