0
\$\begingroup\$

There are various game objects in my scene that share some common characteristics, so I created an interface, like so:

public interface IHasLimitedRangeOfMotionAlongZAxis
{
    float MinimumZ { get; } 
    float MaximumZ { get; } 
}

For certain types that implement this interface, I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity.

I am aware that one approach is to write C# scripts in the Editor folder to implement an ExposePropertyAttribute (see here).

However, this approach is unsatisfactory for two reasons:

  1. My solution is not co-located with my Assets folder. I write my code in a separate solution, and then use pdb2mdb.exe to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C# language features introduced beyond C# 4.0, which nonetheless target .NET Framework 3.5.)
  2. I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code.

Is there a more elegant approach than adding private backing fields with the SerializeField attribute for all of my public properties?

\$\endgroup\$
1
\$\begingroup\$

AFAIK at the moment there aren't solutions different from using [SerializeField] on the private fields of the property or implementing some editor code that exposes properties like the one you linked.

\$\endgroup\$
0
\$\begingroup\$

I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector.

This is not possible. You've declared these properties as read only.

float MinimumZ { get; } //no setter
float MaximumZ { get; } 

No matter what inspector options exist or are possible, or even might be possible for Interface types, you've explicitly denied writing to these properties.

The only option you have is using [SerializeField] on the private backing object.

\$\endgroup\$
  • \$\begingroup\$ I can have a class that implements IHasLimitedRangeOfMotionAlongZAxis with public float MinimumZ { get; set; }, and also inherits from MonoBehaviour. If I assign the script containing this class to a game object, I would like MinimumZ to show up in the inspector. Is this not possible? \$\endgroup\$ – user112729 Mar 16 '18 at 17:03
  • \$\begingroup\$ @MY_G I think at that point you fall under the purview of Galandil's answer. In either case I haven't tried, but I saw your Interface definition and knew there was going to be a problem regardless of what might exist. \$\endgroup\$ – Draco18s Mar 16 '18 at 17:07
  • \$\begingroup\$ Autoproperties are the bane of Unity's Inspector. :D \$\endgroup\$ – Galandil Mar 16 '18 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy