Let’s say I have 5 types of bombs. One is explosive, other one is just a smoke bomb so on and so forth. How can I handle this?
I see 2 ways myself. One would be to create different classes that inherits an Item class which would have “cost” and “damage” fields and overriding method named “Use” to use the bomb.
The other one would be to declare a list to hold instances of Item classes which would also contain “cost” and “damage” fields along with a “name” field. In this case I’d have to serialize and deserialize the list every time + I’d have to hardcode an “item manager” script for different uses of each bomb so it may look ugly.
What would you do in this case?
Definitely the first one. It is a perfect situation the it was made for.
The other main reason besides the look of the code is the reuseability.
Imagine that the next week you come up with an idea that your smoke bomb should have a time field that shows how much time after it disappear. Then you should give your Item class a time field even it has nothing to do with any of the other Items.
And imagine your code if you choose the second way:
void Exploison(Item item)
if(item.name == "smokebomb")
else if(item.name == "flashbang")
and so on...
All your function would look like this and thats a lot of code repeatation. Not to talk about your performance. Even if you use enums instead of strings it is much worse then use polimorphism.
The first thing to consider is how many distinct behaviours you have going on, rather than distinct items. You’ve got explosions versus smoke bombs - but what’s the actual difference in behaviour, other than spawning a different particle effect? Could you actually get away with a single ‘Bomb’ class, but with a ‘ParticleSystem ExplosionEffect’ member variable and setting the damage to 0 for the smoke bomb?
Where possible it’s best to think in terms of ‘has-a’ relationships rather than ‘is-a’ relationships. A smoke bomb has-a explosion particle effect and an AI-visibility-affecting region.
The individual items themselves are then different Prefabs - using the same set of scripts, just configured different ways.
I think different classes would be better for code implementation and also code optimization. and number of scripts does not decrease FPS or any kind of loss in game output.