Liam Ferris
Liam Ferris

Reputation: 1846

How to set initial values for custom inspector fields in unity

I have two similar classes ClassA and ClassB. Both classes contain a bool:

In Class A:

[SerializeField]
private bool _overwrite = true;

public bool overwrite
{
    get { return _overwrite; }
    set { _overwrite = value; }
}

In Class B:

[SerializeField]
private bool _hide = true;

public bool hide
{
    get { return _hide; }
    set { _hide = value; }
}

Both scripts have a CustomEditor script. In both Editor scripts, inside the OnInspectorGUI() method the following two lines are used to add the respective bool's to the Inspector.

ClassA.overwrite = EditorGUILayout.ToggleLeft("Overwrite", ClassA.overwrite);

ClassB.hide = EditorGUILayout.ToggleLeft("Hide", ClassB.hide);


When I add ClassA to a GameObject, the "Overwrite" field is unchecked, however when I add ClassB to a GameObject, the "Hide" field is checked.

I don't understand what is different, or what other factor is involved in setting a default / initial value for a property.

Ideally I want them both to be checked by default.

Any ideas what I might be missing?

Thanks for your time,

Liam

Upvotes: 5

Views: 6278

Answers (2)

Danny Herbert
Danny Herbert

Reputation: 2031

What is grabObject?

If it is the component variable which you have found a reference to in the OnEnable method using the target variable of the Editor script, then simply changing your editor scripts to:

grabObject.overwrite = EditorGUILayout.ToggleLeft("Overwrite", grabObject.overwrite);

and:

grabObject.hide = EditorGUILayout.ToggleLeft("Hide", grabObject.hide);

should solve your problem.

Upvotes: 0

Blair
Blair

Reputation: 6693

The Reset method of MonoBehaviours seems that it will provide the functionality you are looking for. It will look something like this:

void Reset() 
{
    _overwrite = true;
}

Upvotes: 4

Related Questions