How to encapsulate MonoBehaviour behaviours through non MonoBehaviour classes?

I have a weapon. This wepaon consists of different interchangable parts. The player can choose whether it should do fire, ice or poison damage, its attack speed and so on. The player can also choose which type of projectile behaviour to use from a total pool of 9 projectile behaviours.

For instance one projectile behaviour makes it so the projectile flies straight, another one so that it flies in a curve, or is not affected by gravity at all.

Now, in an ideal world I would like to code classes for all of those behaviours and modifications and at the end, have everything come together in a weapon class where a weapon is build based on type of damage, the attack speed and the projectile behaveiours chosen by the player.

My problem: I don’t see another way to code these projectile behaviours other than through an update() function. So my ideal structure of my weapon falls apart, because the projectile behaviour can’t be precoded in a class that will be attached to the Weapon MonoBehaviour. Am I wrong?

If I want to have the choice of all these projectile behaviours, is the only possible solution to hard code them inside the Update() function of my base MonoBehaviour Weapon class with if or switch statements?

Your classes need not all be derived from MonoBehaviour. For things like this, that don’t need Update (or other MonoBehaviour methods) you could have a base Weapon class that is not derived from MonoBehaviour, and make your specific weapons derived from that. Then one of your MonoBehaviours would most likely use those weapons.

Here is a decent article that discusses when not to inherit from MonoBehaviour: When to Inherit from MonoBehaviour - Clark Kromenaker

At the end of the day if you want things to happen in a scene, you need a monobehaviour to make that happen. But you can still use plain C# objects (even serialise them), or reference scriptable objects as a way to have encapsulated and pluggable behaviour.

That said, for specifically projectile behaviour, wouldn’t that make more sense to be on the projectile itself? Then it’s just a matter of spawning a particular prefab.

1 Like