How do i NOT break encapsulation with Unity?

OK Unity supports C#. It doesn't seem to support properties however and only shows public variables in the inspector. This is problematic. For instance I want the developer to use SetHealth(n) instead of Health = 10, because there are some things that happen alongside the value being set.

Of course if I expose Health to the developer, the developer will probably use it. However exposing Health is the only way to display the value in the inspector. Is there a way around this?

2 Answers

2

You can serialize private data with serializefield:

[SerializeField]
private int _health = 100;

To which you could add a public property with only a get accessor (or only a set, or both, either of which can do validation, etc.)

–

Ah, a coder who have the same values and concerns as I do. Well, for once I must say that properties haven't posed much of a deal for me, I have stuck with direct access members for pretty much everything in Unity.

But if you really want to use properties, then you should create your own editor script for your script type. Also you can probably automate a great deal of the gui rendering code by utilizing reflection so you don't have to type out every little member. It is somewhat of a nuisance to go about like this but it's the way you gotta do it. By the way - if you're allowing an editor to set the values chances are you don't want to set the properties either since I assume you'd use properties to run custom code in the get/set method - stuff that might require the game to be running. In that case you can take your editor/reflection a bit further by attributing private members with your own attributes so the editor knows to publish those variables to the editor.

Just setting your storage fields private/protected etc will still cause problems - Unity will not be able to serialize them without adding the SerializeField attribute, just as Mike replied a moment ago.

In coding that isn't unity I find myself employing my oop teachings much strictly for several reasons but the main reason is productivity. The second reason is that unity doesn't perform well with interfaces (especially the editor but also game crashing when recompiling while game is running) unless I script my entire game, in case I feel I could rather use some other engine.

–