Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

unity3d

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;
}
like image 580
Scott Baker Avatar asked Nov 11 '16 18:11

Scott Baker


2 Answers

You can use Auto-Implemented Property Field-Targeted Attributes since Unity 2018.

[field: SerializeField]
public GameObject WrongBallProperty { get; set; }
like image 187
Dan Avatar answered Oct 21 '22 05:10

Dan


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.

like image 32
levelonehuman Avatar answered Oct 21 '22 05:10

levelonehuman