Does [SerializeField] always make variables private?

In the video he says “We still don’t want this to be public to other scripts in our game, so let’s again use [SerializeField]”. Does [SerializeField] always make a variable private and inaccessible to other scripts? Is there a way to access a [SerializeField] variable from another script? Also, is there a difference in access between using [SerializeField] and just putting private before the variable?

Thanks in advance.

No, [SerializeField] has nothing to do with the accessibility of the field in C#. The fields are private because we either don’t specify an access modifier (which defaults to private)

[SerializeField] float speed = 10f;

or we make it private

[SerializeField] private float speed = 10f;

Yes. Make it public although, as the course mentions, we don’t always want this

[SerializeField] public float speed = 10f;

You also don’t need [SerializeField] on a public field to show it in the inspector (properties don’t work, though, unless you use [field: SerializeField] in newer versions of Unity)

It is recommended that you make an ‘accessor’ to get this value, but it all depends on your use case

[SerializeField] float speed = 10f;

// public accessor method
public float GetSpeed()
{
    return speed;
}
// or public read-only property
public float Speed
{
    get
    {
        return speed;
    }
}

Again, [SerializeField] has nothing to do with the accessibility. We add [SerializeField] - which was made by Unity - to show that field in the inspector. If it’s just private, you won’t see the value in the inspector and you won’t be able to adjust the value there.

1 Like

Thanks a lot! That makes a lot more sense now.

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

Privacy & Terms