While public and private access modifiers can be useful for limiting any kind of external access to a variable, the Read Only modifier can be used to prevent a value from being set outside of its constructor.
If constructors are new to you, they’re basically setup functions that are used to set a type’s initial data when it’s created.
Meaning that a read only variable can only be set once, when it’s initialised.
Like this:
public readonly int year = 2024;
You’d generally use read only for data that will be set when it’s created and that will then never change.
This might be a value that is used throughout a script, but that isn’t meant to be modified at any point, not even by the class that created it.
Alternatively, if you want to create a variable that can be modified locally, but that other classes can read, but can’t change, then it’s possible to give a variable public access with private write permissions.
One way to do this is with an auto-implemented property, which can be used to combine a public get with a private set.
Which looks like this:
public float NumberC { get; private set;}
See also: