I was just wondering how to make a never changing number when called at the start of the script ?
So once you have defined it from the Awake() or Start() how can i make it so the number is fixed ?
Even functions can’t change it.
I dont want to provide a definite number, like 2 or 5 or 100 or even 1000000
I want to make a variable so i can change it in the Awake() or Start() function.
And keep it fixed throughout the whole script.
There is no magic to Awake or Start, they are simply methods called by Unity for you.
If they can modify the number, so can any other class method.
Having said that you COULD create a class that holds a value that can only be set once by anyone.
It would look something like this:
class OneTimeFloat {
private float _value;
private bool beenSet=false;
public float Value {
get { return _value;}
set {
if (!beenSet){
_value = value;
beenSet=true;
} else {
throw new Exception("Attempt to reset value of OneTimeFloat");
}
}
}
}
The C# language allows two different ways of defining constants. The first and most obvious is using the “const” keyword. A field that has the const keyword is actually a compile-time constant. So when the code is compiled everywhere you used the constant it will insert the value of that constant.
Const fields can only be initialized when they are declared:
public const int myConstant = 5;
They can’t be changed at runtime as they actually aren’t fields at all. const fields are automatically static.
The second way is using the “readonly” keyword:
public readonly int myReadOnlyField = 20;
A readonly field is an actual field in a class, but it can only initialized from a field initializer at declaration or from a constructor when the class is created. The languages doesn’t allow to change the value any time after the constructor has been called.
So you can’t use Awake or Start to initialize readonly fields. In Unity MonoBehaviour classes readonly fields behave the same as a const field.
Note: As i said readonly fields can’t be changed due to a language restriction. With reflection it actually is possible to change it at runtime since it’s an actual field in the class. However, DON’T DO THIS, EVER! readonly fields are meant to not change their value.
The only way to build a construct that allows setting a value once in Awake or Start is using a class like the one @jeff-kesselman posted.