referencing the base class but still want to use the overridden functions...

hi guys
so i’m trying to build a system that allows me to have various guns in my game that all have the same functions (like fire, reload, etc) but each of those functions should be unique to the gun.

my initial idea was to have an empty gameobject called “weapons” and then put the various gun prefabs in it as children.

each of the guns would then have a unique script on it that would inherit from an abstract class “weapon” and override the fire, reload, etc functons to play its own unique animation or do something else if it needs to.

and the “weapons” parent object would have a “weaponsmanager” script on it that would get each of the children and manage which weapons should be enabled and when the user clicks the mouse it runs the “fire” function etc…

heres an example:

Weapon.cs

public class Weapon: MonoBehaviour{
    public void test()
        {
            Debug.Log("from weapon base");
        }
}

UniqueGun123.cs

public class UniqueGun123: Weapon{
    public void test()
        {
            Debug.Log("overridden ..");
        }
}

WeaponManager.cs

[SerializeField]
    private GameObject gun_temp;


	void Start ()
    {
        
        Weapon reference = GetComponent<Weapon>();

        reference.test();

    }

when i run this and reference the unique gun as the “gun_temp” in the WeaponManager.cs it prints “from weapon base” in the console instead of “overridden …”

so does anyone know a better way i could go about this? since my idea doesn’t seem to work

Your base class’s method has to be virtual in order to be polymorphic.

In your base class:

public virtual void test() // make the method overridable using 'virtual' keyword
{
    ...
}

In your derived classes:

public override void test() // override the method
{
    base.test(); // call base class's implementation, delete this line if not necessary

    ... 
}