Can you make a variable modifiable ONLY by the Inspector?

I want a variable to be modified by ONLY the Inspector, not anywhere else in the code.

For instance, I tried to set the variable to:

public T myVar { get; private set; }

However, this makes it so the variable is no longer editable in the Inspector. Is there anyway around this without exposing the variable to edits from elsewhere in the code?

Thanks so much in advance.

You can make a backing field for your property:

[SerializeField]
private T _myVar;
public T myVar => _myVar;

However, that’s 3 lines… so you could as well use the automatically generated backing field:

[field: SerializeField]
public T myVar { get; private set; }

However (again), this displays the backing field’s name in the inspector, and it’s kinda ugly. So you can use this attribute I wrote to display the right name:

[field: SerializeField, UsePropertyName]
public T myVar { get; private set; }

Unity will not serialize properties. But you can have it serialize a private variable like this:

[SerializeField]
public T myVar = null;

And then expose it with a public getter if you like.

I usually make sure to set a default value for these, even if it’s null, because otherwise they can cause “this variable is never assigned and will always have its default value” compiler warnings in Visual Studio.