- Home /
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?
Answer by CHPedersen · Mar 04, 2015 at 11:36 AM
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;
Answer by _foa · Mar 04, 2015 at 11:31 AM
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: http://docs.unity3d.com/Manual/VariablesAndTheInspector.html
Hope this helps :)
If you declare a private setter then you want to make sure the variable is read-only from other classes. If you make it public then it becomes contradictory.
Answer by N-8-D-e-v · Nov 30, 2020 at 01:08 PM
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
Your answer
Follow this Question
Related Questions
How do I make child classes in a list editable from the Inspector? 1 Answer
Getter / Setter and Variable Scope Question? 1 Answer
Array not updating in inspector 0 Answers
Serializable class using generics 3 Answers
Getters issue... 1 Answer