Home > Mobile >  Polymorphism in Unity with mono-behaviour
Polymorphism in Unity with mono-behaviour

Time:01-11

I have a problem with polymorphism in unity. I want to create a abstract base "Gun" class to represent guns in my doom-clone game. Next i want to create some children classes like "shotgun","pistol" and so on then make for example list of "Guns" when i store each children. But when i want to do this i need to derive from my base "Gun" class, and not from mono behaviour. That way i cannot store references to for example animator, or audio Source in my children scripts like Shotgun. I want the sound of shotgun to be stored inside shotgun script, so when i want to play it i just call specific object method. But without mono behaviour it seems impossible. I don't think scriptable objects solve my problem either. What should i do then?

CodePudding user response:

Just have

public abstract class Gun : MonoBehaviour
{ 
    // common members like e.g.
    // either private -> only this class has access
    // or protected -> only this class and inherited classes have accss
    // or public -> every other type has access
    [SerializeField] protected AudioSource audio;
    [SerializeField] protected Animator animator;

    // abstract methods all inheritors HAVE TO implement
    // maybe virtual methods inheritors CAN overrule or extend but don't have to
    // other common private/protected/public methods etc
    public virtual void Shoot()
    {
        // reduce one bullet
        // play your sound file etc
    }
}
 

and then each in its own file

public class Pistol : Gun 
{ 
    
} 

and

public class Shutgun : Gun 
{ 
     
} 
  •  Tags:  
  • Related