Separate Classes for Projectiles

So, instead of following what they have instructed us in doing and having one projectile class, I made one for enemies and one for the player.

This has allowed me to change the prefab of the projectile so they look different. I also have control over the damage done by the different projectiles. I don’t have to think about layers since there is no interaction between the player and the player’s projectiles, only the enemy’s projectiles.

Their way seems way more complicated to me. Where am I wrong?

There is no real “right” or “wrong” here, your way may have its advantages compared to theirs.

However it does make sense, in an object-oriented programming context, to have one unique class defining a unique “type” of object. So a projectile, be it friendly or unfriendly, is just one type of object. The properties and methods that a projectile object has are the same regardless of who fires it. In your solution, you had to write those properties and methods twice, whereas they only did it once. If you wanted to add a third projectile type, you would probably need to write a third class. If you wanted to make a change to your projectiles, you’d have to do it in each of those classes, instead of the overarching Projectile class.

So hopefully you can see how one way is more scalable than the other.
Anyway, that’s my take on the subject, other people could very well see things differently.

3 Likes

Another approach would be to create a base class which both enemy and player projectiles could inherit from.

Where ever possible you shpuld look to remove duplication. A good method to determine which fields/properties/methods could live in the base class would be to grab a pencil and make a list all of the above for both enemy and player projectiles. Whatever is common shouldnt need to be duplicated. For example, if both projectiles will have a prefab you could pop that into the base class, note, it isnt hard coded as to which prefab, just that there will be one.

Projectiles by definition will most likely have a direction, a speed, perhaps a duration before they fizzle out and so on.

The specific type of projectile, player or enemy, or indeed multiple types of those (lasers, rockets etc) would then have methods which were specific to their needs. A smart bomb for example may detonate after so many seconds.

Hope this is of use.

3 Likes

Thank you very much! That actually makes a lot of sense to me, I’m going to update my code a little bit to remove some redundancies.

1 Like

Thank you so much! Really appreciate the input and am going to update some classes.

1 Like

You are more than welcome :slight_smile:

Glad I could help :wink:

1 Like

Actually, I used 2 different prefabs and a single class. There’s no need to change the class unless you wanted different behaviours for the projectiles.