Hi,
I’m making a tower-defense type of game. When making a basic tower, I created a Targeting System script and a Standard Shooting script (find a target and fire at it), and its Damage, Range, Fire Rate and RotationSpeed, among other values, reside in this script. However, there may be another type of tower (like an ice tower that freezes enemies around it) which needs a different script to manage its behaviour, as it doesn’t shoot in the convencional way.
The problem is that I want a menu to pop up when you click on the tower once it’s built, showing its stats (Damage, Range, FireRate…), but I can’t acces the tower’s values in the Menu script because the script in which these values reside depend on the tower (the Basic Tower stores these values in the Standard Shooting script, but the ice tower stores them in its own script), so I can’t reference a specific Script, as said tower may not have it.
What would be the best way to store the values of each tower, while allowing them to have their separate behaviour scripts, which inherit the values from their tower, not the script itself?
I have researched a bit and I think Inheritance, Scriptable Objects or just creating a TowerAttributes script that stores the Towers’ values might help but I don’t know which is the best and more organized way to approach the problem.
Thanks a lot!
I’d suggest expressing this shared information via C# interfaces. Thus you can have a variety of different components that express similar properties. You could also use inheritance, but interfaces are the more flexible options as you don’t need to couple yourself to any particular concrete type.
Definitely worth doing some reading as there’s lots of information how you can use C# interfaces in Unity: Interfaces in Unity (how and when to use them)
When it comes to UI though, understand that your UI should just present information to the player, along with some ways to modify whatever the UI is targeting. Two ways you could approach this with a tower deference game is either:
- Scan a tower for a set of interfaces for displaying to the player. Said interfaces could also provide the necessary API for upgrading, selling, etc.
- Allow towers to provide their own UI prefab/implementation.
The former being more automatic, but if towers have very specific UI functionality required the latter may be necessary. You could have both, of course, by having an interface that outlines a custom UI implementation, checking for said interface first and using that if found, otherwise default to the automatic UI.
1 Like
I haven’t heard about Interfaces but I will take a look at the link and do a little investigation.
Thank you so much for writing such a detailed and informative solution in such a short time
1 Like