Make a public variable with a private setter appear in inspector

Hi

I have what I think would be a common enough situation.

I have variable which is public but has a private setter.

public float moveSpeed{get; private set;}

However this WILL NOT show up in the inspector even with [Serializable]. Turns out even THIS won’t show up in the inspector:

public float moveSpeed{get; set;}

Do you know how I can force this to show up in the inspector?

Making variables public just to facilitate serialization in Unity is an anti-pattern and should be avoided in my opinion. I like using the [SerializeField] attribute instead. That way, you can have private variables show up in the inspector while still exposing them with a property that has a public getter and a private setter in C#. It looks like this:

public int Test { get { return test; } private set { test = value; } }

[SerializeField]
private int test = 0;

You can also now write this as:

[field: SerializeField] public float moveSpeed { get; set; }

And you even do things like this, where you can add headers in the inspector to work with this shorthand, set default values, and make the set private:

[field: Header("Player speed settings")]
    [field: SerializeField] public float moveSpeed { get; private set; } = 5f

You could just make it a private variable with the [SerializeField] attribute, and then create a getter method to return the variable like so

    public string GetMainMenuSceneName()
    {
        return mainMenuSceneName;
    }

which is what I just did

I believe that auto properties or properties will not show up in the Inspector.
You need to declare moveSpeed as a simple public float variable.

See: Unity - Manual: Variables and the Inspector

Hope this helps :slight_smile:

interesting information