Reputation: 180
I am currently working on a game in Unity, and I am having a bad time figuring out how I would go about managing the different tile types.
Since there are a lot of different kinds of tiles (containers, extractors, research devices, et cetera), I need a way to save, load and access this data in a way that is easy to expand.
My first thought was to use inheritance: For example, all components that are a container tile, derive from a class called ContainerTile, which derives from TileBehaviour. If the player destroys a container tile, the player script will check if there is any TileBehaviour component on the target block and then use the destroy function. if he wants to open a container, the script will use check if there is any ContainerTIle component on the target block and use the open function.
The major flaw with this is that saving data does not work this way: when saving all containerTile data as TileBehaviour data, it only saves the data that is part of the tileBehaviour class, and all other data (like which items are in the container) is lost.
Can someone tell me what I should do with this?
Thanks.
Upvotes: 0
Views: 259
Reputation: 8536
As said by @UnholySheep in the comment, it looks like your code is begging for ScriptableObject
.
They are like MonoBehaviour
, but they are not attached to GameObject (so, no transforms and stuff). They can have inspectors and receive some messages like OnDestroy...
Inheritance works like a charm with them. You can also make abstract derived classes. Also, serialization is built-in.
You define an abstract SerializedObject
named Tile
, for example, then other child classes ContainerTile
, ExtractorTile
...
You can create assets of those classes with custom parameters and reference them in components, much like Prefabs, but they are all the same object. Or, you can instantiate them at runtime also.
They are good for managers (safe Singleton), enum on steroids, plain data, transferring data through scenes / projects...
I highly recommend you this video for ideas on how to use them, besides of course Unity's own tutorials on the matter, like this and this
Upvotes: 1