How to create read-only variables

Hello everyone,

Is there any way to create read-only variables such as the ones in Time class without using get functions? (In both C# and Unity’s JS)

In addition to drawcode’s correct answer, another solution is to put either the readonly or const keyword in the variable declaration. For example public readonly int currentTime;.

Adding the readonly keyword will make the variable only settable in the constructor or using a field initializer. Const will only allow the variable to be initialized with a field initializer.

This only works on C# as far as I know.

In C# it needs to be a property, properties can be readonly but only allowing a get

public class MyBehaviour : MonoBehaviour {
    private float _currentSpeed = 1.0f;

    public float currentSpeed {
        get {
            return _currentSpeed;
        }    
    }
}

If you want them accessible like the Time class make them static

public class MyBehaviour : MonoBehaviour {
    private static float _currentSpeed = 1.0f;

    public static float currentSpeed {
        get {
            return _currentSpeed;
        }    
    }
}

You can access the latter as MyBehaviour.currentSpeed;

If you mean changing currently existing Unity ReadOnly variables, like resetting Time.time to 0, then no. ReadOnly really does mean you can’t change it.

The work around (which I think is what your reference to GET was) is to make your own copy of the variable. Say for Time, create your own gameTime, add Time.deltaTime each update and have the entire program check gameTime instead of Time.time. If your program is already full of Time.time references – well, that’s what find and replace is for.