Unity Weapons system: Components VS Subclassing

I’m working on a 2D aquarium battle arena, for each character in the arena, they will have a left hand and right hand weapon equipped.

I’m now sketching out how should I model the components. As a start I’m thinking to have a left and right hand behaviour script which implements and stores the “Actions” and modifiers to each arms (e.g. strength). Then I’ll have a field to store a prefab of a weapon assigned.

Here comes my question: Whether should I create a Weapon behavior class that serves all variants of weapons (sword, knife, axes). This sticks better with the component approach but I’ll need to stuff all weapon logic in the component.

Or to create a generic Weapon Monobehavior class and subclass it for each individual weapon, which seems more desirable if I want to separate the logic of different weapons, such as how the animations are rendered.

What do you prefer?

I would definitely go with the second approach. You can make an abstract class that extends MonoBehaviour (or even better, ScriptableObject, if you’re familiar with them)

public abstract class AbstractWeaponBehaviour : MonoBehaviour {

	public abstract void Fire();

	public abstract void SecondaryFire();

	public abstract void Reload();
}

this way you can use this as base class for each weapon, and use polymorphism like a boss

On your player you then have a WeaponController component look like this

    public class WeaponController : MonoBehaviour {

    	public AbstractWeaponBehaviour weaponBehaviour;

    	public void Fire() {
    		weaponBehaviour.Fire ();
    	}
    	public void SecondaryFire() {
    		weaponBehaviour.SecondaryFire ();
    	}
    	public void Reload() {
    		weaponBehaviour.Reload ();
	}
}

This way you can plug any of your implementations of AbstractWeaponBehaviour into your WeaponController

Privacy & Terms