ScottSEA ScottSEA - 28 days ago 7
C# Question

In Unity, can I expose C# *Properties* in the Inspector Window?

Scripts are normally written so that public fields are exposed in the Inspector; is there some way to use properties instead?

// instead of this
public GameObject wrongBall;

// is there some way to do this (to trigger an event in the setter, for instance)
// and have it show up in the inspector window?
public GameObject WrongBallProperty
{
get;
set;
}

Answer

Sort of.

You can't directly use a property in the inspector, but you can create your property with a backing field:

public GameObject WrongBallProperty {
    get { return this.wrongBallProperty; }
    set { //do whatever }
}

[SerializeField]
private gameObject wrongBallProperty;

This will display wrongBallProperty in the inspector, and allow you to do whatever logic you need in get and set. See the SerializeField reference for more info.