Hertzole
Hertzole

Reputation: 73

C# & Unity - Pass property as object and get property name

I'm trying to work on a system for my Unity3D game that easily allows me to show properties by just passing them into a function. But in order to make it work, I need the property name and I can't properly get it. Right now, this is what I've made.
In my "inspector script" I basically just to this. This will call an inherited function that should handle the "other" stuff. In this case, 'value' is Unity's Transform component and 'position' is a Vector3 property.

DoUI(value.position);

The "DoUI" function

protected virtual void DoUI(object property)
{
    Type type = property.GetType();
    Debug.Log("Type ToString: " + type.ToString() + " | Name: " + type.Name + " | Full Name: " + type.FullName);
}

Right now, the function only prints a debug message and by looking at that, I can see that it's not correct. It gives me the type name, in this case, Vector3, and yes, I know that you can clearly see that by looking at the code.

So the question remains, how can I get a property name by just passing it "as is" without the user having to do any complicated reflection calls? That's what "DoUI" is for.

Upvotes: 2

Views: 1789

Answers (2)

CShark
CShark

Reputation: 1563

Serialized Objects and Serialized Properties are probably what you look for. They are used even by the Unity internal inspector and it should be no problem to adopt them.

To use Serialized Properties you'll first need to construct a SerializedObject with the instance you want to edit. Then use the method FindPropertyRelative (or FindProperty when you're at the root level) to get the SerializedProperty of your object. You can then access the name and type of the property and aqcuire/set the value or even dig further down for nested properties. To Update the Serialized Representation, call Update on the Serialized Object. To write your changes back to the Object, use ApplyModifiedProperties.

There are two main caveats though. The class needs to either inherit ScriptableObject or MonoBehaviour or needs the Serializable flag. And you can only access "Properties" that unity can serialize, which excludes Properties ironically. You'll either need a public field or a private backing field for the property which is marked with the Attribute SerializeField.

Upvotes: 1

Bizhan
Bizhan

Reputation: 17085

In C# 6 you can use nameof operator. like nameof(myClass.MyProp) which returns a string "MyProp"

However Unity 5 supports C# 4 so you have to use this workaround for lack of nameof in C# versions prior to 6

or this one

Upvotes: 1

Related Questions