- Home /
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)
Answer by drawcode · Aug 04, 2012 at 09:23 AM
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;
Answer by Jamora · Aug 04, 2013 at 08:05 AM
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.
Answer by Owen-Reynolds · Aug 04, 2012 at 01:44 PM
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.
No, that wasn't my question. I know that a read-only variable cannot be changed. Although, you did give a good solution for doing that
Your answer
Follow this Question
Related Questions
Lower player's health from separate script. 2 Answers
Distribute terrain in zones 3 Answers
GetComponent, What is it ? 1 Answer
Make a variable start at 10 and count down until 0 3 Answers