Have member variables in Unity Version 2018.2.6f1 changed?

If I use only “int level;” in my code, then I can’t see the member variable in the Inspector.
With “public” it works!
Has the Version 2018 such a change? Why is Level with capital first letter in the Inspector?


Hi Norbert,

No, it hasn’t changed, well, not from that perspective anyway.

In C# the default access modifier is private, so, you if you don’t specify the access modifier, private is used anyway. If the member variable is private, it won’t be displayed in the Inspector.

You can however use the [SerializeField] attribute to obtain the best of both worlds, as you don’t really want to be setting every member variable to public just so that they can be seen in the Inspector, as the consequences of this could be disastrous.

Examples;

using UnityEngine;

public class Example : MonoBehaviour
{
    int level;    // this defaults to private and isn't visible in the Inspector
}
using UnityEngine;

public class Example : MonoBehaviour
{
    public int level;    // this has the public access modifier so it will be displayed in the Inspector, but also every other class will be able to see/access it also
}
using UnityEngine;

public class Example : MonoBehaviour
{
    [SerializeField]
    int level;    // this defaults to being private, despite private not being specified, but will appear in the Inspector as the member variable is serialized
}

Personally, I tend to always specify the access modifier and not rely on any defaults. I do this with the Start and Update methods also, e.g.

using UnityEngine;

public class Example : MonoBehaviour
{
    [SerializeField]
    private int level;

    private void Start()
    {
        // ...
    }

    private void Update()
    {
        // ...
    }
}

Why is Level with capital first letter in the Inspector?

Unity implements a nicify script which uppercases the first letter of your variable names, it also removes characters used in popular naming conventions such as _ and m_, it will also separate words based upon capitalisation. Example;

private int _myMemberVariable;

This will appear as “My Member Variable” within the Inspector.

Hope this helps. :slight_smile:


See also;

1 Like

Hi Rob,
Now I have learned a lot from your detailed answer and your note to “Access Modifiers”, “[SerializeField]” …
Thanks you very much for this!
I think your tutorials of Unity, C# and Blender guide me to an exciting new world (Gamedeveloping)!

1 Like

You’re very welcome Norbert :slight_smile:

I can’t take credit for the courses but I am glad you are really enjoying them :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms