Some time ago I started working with Unity and I still struggle with the issue of tightly coupled scripts. How can I structure my code to avoid this problem?
For example:
I want to have health and death systems in separate scripts. I also want to have different interchangeable walking scripts that allow me to change the way the player character is moved (physics-based, inertial controls like in Mario versus tight, twitchy controls like in Super Meat Boy). The Health script needs to hold a reference to the Death script, so that it can trigger the Die() method when the players health reaches 0. The Death script should hold some reference to the walking script used, to disable walking on death (I'm tired of zombies).
I would normally create interfaces, like IWalking
, IHealth
and IDeath
, so that I can change these elements at a whim without breaking the rest of my code. I would have them set up by a separate script on the player object, say PlayerScriptDependancyInjector
. Maybe that script would have public IWalking
, IHealth
and IDeath
attributes, so that the dependencies can be set by the level designer from the inspector by dragging and dropping appropriate scripts.
That would allow me to simply add behaviors to game objects easily and not worry about hard-coded dependencies.
The problem in Unity
The problem is that in Unity I can't expose interfaces in the inspector, and if I write my own inspectors, the references wont get serialized, and it's a lot of unnecessary work. That's why I'm left with writing tightly-coupled code. My Death
script exposes a reference to an InertiveWalking
script. But if I decide I want the player character to control tightly, I cant just drag and drop the TightWalking
script, I need to change the Death
script. That sucks. I can deal with it, but my soul cries every time I do something like this.
Whats the preferred alternative to interfaces in Unity? How do I fix this problem? I found this, but it tells me what I already know, and it does not tell me how to do that in Unity! This too discusses what should be done, not how, it does not address the issue of tight coupling between scripts.
All in all I feel those are written for people who came to Unity with a game design background who just learn how to code, and there is very little resources on Unity for regular developers. Is there any standard way to structure your code in Unity, or do I have to figure out my own method?
No comments:
Post a Comment